标签:src saveas filetype 主菜单 背景颜色 let init png post
"""记事本程序"""
from tkinter import *
from tkinter.filedialog import *
from tkinter.colorchooser import *
class Application(Frame):
def __init__(self, master=None):
super().__init__(master) # super()代表的是父类的定义,而不是父类对象
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
#创建主菜单
menuBar = Menu(root)
#创建子菜单
menuFile = Menu(menuBar)
menuEdit = Menu(menuBar)
menuHelp = Menu(menuBar)
#将子菜单添加到主菜单上
menuBar.add_cascade(label="文件(F)", menu=menuFile)
menuBar.add_cascade(label="编辑(E)", menu=menuEdit)
menuBar.add_cascade(label="帮助(H)", menu=menuHelp)
#添加菜单选项
menuFile.add_command(label="新建", accelerator="ctrl+n", command=self.newFile)
menuFile.add_command(label="打开", accelerator="ctrl+o", command=self.openFile)
menuFile.add_command(label="保存", accelerator="ctrl+s", command=self.saveFile)
menuFile.add_separator() # 添加分割线
menuFile.add_command(label="退出", accelerator="ctrl+q", command=self.exit)
#将主窗口添加到根窗口
root["menu"] = menuBar
#编辑文本区
self.textpad = Text(root, width=600, height=30)
self.textpad.pack()
#编辑上下菜单
self.rightMenu = Menu(root)
self.rightMenu.add_command(label="背景颜色", command=self.openAskColor)
#绑定事件
root.bind("<Button-3>", self.createRightMenu)
root.bind("<Control-n>", lambda event: self.newFile())
root.bind("<Control-o>", lambda event: self.openFile())
root.bind("<Control-s>", lambda event: self.saveFile())
root.bind("<Control-q>", lambda event: self.exit())
def openFile(self):
self.textpad.delete(1.0, END)
with askopenfile(title="打开文本文件") as f: #返回打开的文件对象
self.textpad.insert(INSERT, f.read())
self.filename=f.name
def newFile(self):
self.textpad.delete(1.0, END)
self.filename=asksaveasfilename(title="打开新建文件", initialfile="未命名.txt",
filetype=[("文本文档", "*.txt")],
defaultextension="*.txt") #返回的是保存的文件名
self.saveFile()
def exit(self):
root.quit()
def saveFile(self):
with open(self.filename, "w") as f:
f.write(self.textpad.get(1.0, END))
# with open(self.filename, "w") as f:
# f.write(self.textpad.get(1.0, END))
def openAskColor(self):
bgcolor = askcolor(color="red", title="背景颜色")
self.textpad.config(bg=bgcolor[1])
def createRightMenu(self, event):
self.rightMenu.post(event.x_root, event.y_root)
if __name__ == ‘__main__‘:
root = Tk()
root.geometry("600x250+200+300")
root.title("新建文本文档")
app = Application(master=root)
root.mainloop()
测试成功:
标签:src saveas filetype 主菜单 背景颜色 let init png post
原文地址:https://www.cnblogs.com/dangjingwei/p/12284444.html