打开和保存修改文件的实现

 1 from tkinter.filedialog import *
 2 from tkinter.colorchooser import *
 3 
 4 
 5 class Application(Frame):
 6     def __init__(self, master=None):
 7         super().__init__(master)
 8         self.master = master
 9         self.textpad = None
10         self.pack()
11         self.createWidget()
12 
13     def createWidget(self):
14         menubar = Menu(root)
15         menuFile = Menu(menubar)
16         menuEdit = Menu(menubar)
17         menuHelp = Menu(menubar)
18 
19         menubar.add_cascade(label='文件(F)', menu=menuFile)
20         menubar.add_cascade(label='编辑(E)', menu=menuEdit)
21         menubar.add_cascade(label='帮助(H)', menu=menuHelp)
22 
23         menuFile.add_command(label='新建', accelerator='ctrl+n', command=self.test)
24         menuFile.add_command(label='打开', accelerator='ctrl+o', command=self.openfile)
25         menuFile.add_command(label='保存', accelerator='ctrl+s', command=self.savefile)
26         menuFile.add_command(label='退出', accelerator='ctrl+q', command=self.exit)
27 
28         root['menu'] = menubar
29 
30         self.textpad = Text(root, width=50, height=30)
31         self.textpad.pack()
32         self.contextMenu = Menu(root)
33         self.contextMenu.add_command(label='背景颜色', command=self.test)
34 
35         root.bind('<Button-3>', self.createContextMenu)
36 
37     def test(self):
38         pass
39 
40     def openfile(self):
41         self.textpad.delete('1.0', 'end')
42         with askopenfile(title='打开文本文件')as f:
43             self.textpad.insert(INSERT, f.read())
44             self.filename = f.name
45 
46     def savefile(self):
47         with open(self.filename, 'w')as f:
48             c = self.textpad.get(1.0, END)
49             f.write()
50 
51     def exit(self):
52         root.quit()
53 
54     def createContextMenu(self, event):
55         self.contextMenu.post(event.x_root, event.y_root)
56 
57 
58 if __name__ == '__main__':
59     root = Tk()
60     root.geometry('450x300+100+100')
61     root.title = '笔记本'
62     app = Application(master=root)
63     root.mainloop()