新建文件&背景色改变&快捷键功能
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.newfile) 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.openAskColor) 34 35 root.bind('<Button-3>', self.createContextMenu) 36 root.bind('<Control-n>', lambda event: self.newfile()) 37 root.bind('<Control-o>', lambda event: self.openfile()) 38 root.bind('<Control-s>', lambda event: self.savefile()) 39 root.bind('<Control-q>', lambda event: self.exit()) 40 41 def openAskColor(self): 42 s1 = askcolor(color='red', title='选择背景色') 43 self.textpad.config(bg=s1[1]) 44 45 def openfile(self): 46 self.textpad.delete('1.0', 'end') 47 with askopenfile(title='打开文本文件')as f: 48 self.textpad.insert(INSERT, f.read()) 49 self.filename = f.name 50 51 def savefile(self): 52 with open(self.filename, 'w')as f: 53 c = self.textpad.get(1.0, END) 54 f.write() 55 56 def exit(self): 57 root.quit() 58 59 def newfile(self): 60 self.filename = asksaveasfile(title='另存为', initialfile='未命名.txt', filetypes=['文本文档', '*.txt'], dedfaultextension='.txt') 61 self.savefile() 62 63 def createContextMenu(self, event): 64 self.contextMenu.post(event.x_root, event.y_root) 65 66 67 if __name__ == '__main__': 68 root = Tk() 69 root.geometry('450x300+100+100') 70 root.title = '笔记本' 71 app = Application(master=root) 72 root.mainloop()