老师您好,我这个打开老是乱码怎么办?
#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.master = master
self.pack()
self.file_name = None
self.textpad = None
self.create_widget()
def create_widget(self):
# 设置主菜单
menu_import = Menu(root)
# 设置子菜单
menu_file = Menu(menu_import)
menu_edit = Menu(menu_import)
menu_help = Menu(menu_import)
menu_import.add_cascade(label="文件(F)", menu=menu_file)
menu_import.add_cascade(label="编辑(E)", menu=menu_edit)
menu_import.add_cascade(label="帮助(H)", menu=menu_help)
# 设置可用功能
menu_file.add_command(label="新建", accelerator="ctrl+n", command=self.method_new_file)
menu_file.add_command(label="打开", accelerator="ctrl+t", command=self.method_open_file)
menu_file.add_command(label="保存", accelerator="ctrl+r", command=self.save_file)
menu_file.add_command(label="退出", accelerator="ctrl+o", command=self.method_quit)
# 设置文本框
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["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()
if __name__ == "__main__":
root = Tk()
root.geometry("400x400+500+200")
root.title("记事本的应用")
app = Application(master=root)
root.mainloop()

