"""开发一个简单的记事本。
包含:新建、保存、修改文本内容、退出
包含:各种快捷建的处理
version 1.0
"""
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.textpad = None # textpad代表Text文本框对象
self.filename = None # filename代表打开文本文件的名字
self.contextMenu = None # contextMenu代表上下文菜单对象
self.pack()
self.create_widget()
def create_widget(self):
"""创建主菜单栏"""
menubar = Menu(root)
# 创建子菜单
menu_file = Menu(menubar)
menu_edit = Menu(menubar)
menu_help = Menu(menubar)
# 将子菜单加入到主菜单栏
menubar.add_cascade(label="文件(F)", menu=menu_file)
menubar.add_cascade(label="编辑(E)", menu=menu_edit)
menubar.add_cascade(label="帮助(H)", menu=menu_help)
# 添加菜单项
menu_file.add_command(label="新建", accelerator="ctrl+n", command=self.newfile)
menu_file.add_command(label="打开", accelerator="ctrl+o", command=self.openfile)
menu_file.add_command(label="保存", accelerator="ctrl+s", command=self.savefile)
menu_file.add_command(label="退出", accelerator="ctrl+q", command=self.exit)
# 将主菜单栏加到根窗口
root["menu"] = menubar
# 添加快捷键事件梳理
root.bind("<Control-n>", lambda event: self.newfile())
root.bind("<Control-o>", lambda event: self.openfile())
root.bind("<Control-q>", lambda event: self.exit())
# 文本编辑区
self.textpad = Text(root, width=50, height=30)
self.textpad.pack()
# 创建上下菜单
self.contextMenu = Menu(root)
self.contextMenu.add_command(label="背景颜色", command=self.openAskColor)
# 为右键绑定事件
root.bind("<Button-3>", self.createContextMenu)
def newfile(self):
self.textpad.delete('1.0', 'end')
self.filename = asksaveasfilename(title="另存为", initialdir='未命名.txt', filetypes=[("文本文档", "*.txt")], defaultextension='.txt')
print(self.filename)
self.savefile()
def openfile(self):
self.textpad.delete('1.0', 'end')
with askopenfile(title="打开文件") as f:
self.textpad.insert(INSERT, f.read())
self.filename = f.name
print(f.name)
def savefile(self):
with open(self.filename, 'w') as f:
c = self.textpad.get(1.0, END)
f.write(c)
def exit(self):
root.quit()
def openAskColor(self):
s1 = askcolor(color="red", title="选择背景色")
self.textpad.config(bg=s1[1])
def createContextMenu(self, event):
"""菜单在鼠标右键单击坐标处显示"""
self.contextMenu.post(event.x_root, event.y_root)
if __name__ == '__main__':
root = Tk()
root.geometry("450x300+200+300")
root.title("明算软件的简易记事本")
app = Application(master=root)
root.mainloop()
开发一个简单的记事本
扫描二维码,在手机上阅读