2014年11月21日金曜日

開発環境

Practical Programming: An Introduction to Computer Science Using Python 3 (Pragmatic Programmers) (Paul Gries (著)、Jennifer Campbell (著)、Jason Montojo (著)、Lynn Beighley (編集)、Pragmatic Bookshelf)のChapter 16(Creating Graphical User Interfaces)、16.7(Exercises) 6.を解いてみる。

16.7(Exercises) 6.

コード(BBEdit)

sample6.py

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import tkinter
import tkinter.filedialog as dialog

class Editor:
    def __init__(self, parent):
        self.parent = parent
        self.frame = tkinter.Frame(parent)
        self.frame.pack()
        self.text = tkinter.Text(self.frame)
        self.text.pack()
        menubar = tkinter.Menu(self.frame)
        filemenu = tkinter.Menu(menubar)
        filemenu.add_command(label='Save',
                                  command=lambda:self.save(self.text))
        filemenu.add_command(label='Quit',
                                  command=lambda :self.quit())
        menubar.add_cascade(label = 'File',
                                 menu=filemenu)
        parent.config(menu=menubar)
        
    def save(self, text):
        data = self.text.get('0.0', tkinter.END)
        filename = dialog.asksaveasfilename(parent=self.parent,
                                            filetypes=[('Text', '*.txt')])
        title = 'Save as...'
        with open(filename, 'w') as writer:
            writer.write(data)
            
    def quit(self):
        self.parent.destroy()
        
if __name__ == '__main__':
    window = tkinter.Tk()
    app = Editor(window)
    window.mainloop()

入出力結果(Terminal, IPython)

$ ./sample6.py
$

0 コメント:

コメントを投稿