老师您好,请问一下
#coding=utf-8
from tkinter import *
from tkinter.filedialog import *
from tkinter.colorchooser import *
#构造方法
class Application(Frame):
def __init__(self, master):
super().__init__(master)
self.create_widget()
def create_widget(self):
# 设置主菜单
menu_import = Menu(root)
# 设置子菜单
self.menu_file = Menu(menu_import)
menu_edit = Menu(menu_import)
menu_help = Menu(menu_import)
menu_import.add_cascade(label="文件(F)", menu=self.menu_file)
menu_import.add_cascade(label="编辑(E)", menu=menu_edit)
menu_import.add_cascade(label="帮助(H)", menu=menu_help)
# 设置可用功能
self.menu_file.add_command(label="新建", accelerator="ctrl+n", command=self.method_new_file)
self.menu_file.add_command(label="打开", accelerator="ctrl+t", command=self.method_open_file)
self.menu_file.add_command(label="保存", accelerator="ctrl+r", command=self.save_file)
self.menu_file.add_separator() # 添加分割线
self.menu_file.add_command(label="退出", accelerator="ctrl+o", command=self.method_quit)
# 创建上下菜单
self.contexMenu = Menu(root)
self.contexMenu.add_command(label="背景颜色", command=self.method_colo)
# 设置文本框
self.textpad = Text(root, width=40, height=30, bg="gray")
self.textpad.pack()
# 添加快捷方式
root.bind("<Control-n>", lambda event: self.method_new_file())
root.bind("<Control-t>", lambda event: self.method_open_file())
root.bind("<Control-r>", lambda event: self.save_file())
root.bind("<Control-o>", lambda event: self.method_quit())
root.bind("<Button-3>", lambda event: self.method_colo())
# 将主菜单放入根窗口
root["menu"] = menu_import
# 建设可用功能的方法
def method_new_file(self):
self.file_name = asksaveasfilename(title="另存为", initialfile="未命名.txt",
filetypes =[("文本文档", "*.txt")], defaultextension=".txt")
print(self.file_name)
self.save_file()
def method_open_file(self):
self.textpad.delete("1.0", "end")
with askopenfile(title="打开文件")as f:
self.textpad.insert(INSERT, f.read())
self.file_name = f.name
print(f.name)
def save_file(self):
with open(self.file_name, "w", encoding="utf_8")as f:
c = self.textpad.get(1.0, END)
f.write(c)
def method_quit(self):
root.quit()
def method_colo(self):
colo_1 = askcolor(title="请选择颜色", color="gray")
self.textpad.config(bg=colo_1[1])
if __name__ == "__main__":
root = Tk()
root.geometry("400x400+500+200")
root.title("记事本的应用")
app = Application(master=root)
root.mainloop()
1,这里所说的创建上下菜单感觉可有可无啊,都可以正常运行而且运行过程和结果看起来都一样,那么还有写这个的必要吗?
2,self是调用类里面的类属性,可是就按我这个写的话似乎也没有影响,那么在__int__中写self的作业是什么?为了以后查看方便吗?