因此,我正在使用Python 3x和Tkinter创建一个记事本应用程序。每个功能都可以正常工作,但“保存”却不能,Idek为什么。 这是代码:
textArea = Text(root)
menuBar = Menu(root)
fileMenu = Menu(menuBar, tearoff=0)
editMenu = Menu(menuBar, tearoff=0)
helpMenu = Menu(menuBar, tearoff=0)
scrollBar = Scrollbar(textArea)
file = None
def init():
textArea.grid(sticky=N + E + S + W)
fileMenu.add_command(label="New", command=newFile)
fileMenu.add_command(label="Open", command=openFile)
fileMenu.add_command(label="Save", command=saveFile)
fileMenu.add_separator()
fileMenu.add_command(label="Exit", command=exitApp)
menuBar.add_cascade(label="File", menu=fileMenu)
root.config(menu=menuBar)
scrollBar.pack(side=RIGHT, fill=Y)
scrollBar.config(command=textArea.yview)
textArea.config(yscrollcommand=scrollBar.set)
def newFile():
root.title('Untitled - Notepad')
file = None
textArea.delete(1.0, END)
def openFile():
file = tkinter.filedialog.askopenfilename(defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents", "*.txt")])
if file == '':
file = None
else:
root.title(os.path.basename(file) + " - Notepad")
textArea.delete(1.0, END)
file = open(file, "r")
textArea.insert(1.0, file.read())
file.close()
def saveFile():
if file == None:
file = tkinter.filedialog.asksaveasfilename(defaultextension=".txt",
initialfilename="Untitled.txt",
filetypes=[("All Files", "*.*"),
("Text Documents", "*.txt")])
if file == '':
file = None
else:
file = open(file, "w")
file.write(textArea.get(1.0, END))
file.close()
root.title(os.path.basename(file) + " - Notepad")
else:
file = open(file, "w")
file.write(textArea.get(1.0, END))
file.close()
def exitApp():
exit()
init()
root.mainloop()
调试器说,当我使用“文件”作为引用但使用idk做保存功能的另一种方法时,错误在第66行。
if file == None: