【发布时间】:2019-12-03 18:25:56
【问题描述】:
我正在尝试构建一个记事本,但我的保存和另存为按钮有问题,因为 TextField 中的内容不保存,文本文档总是返回空,这是我的代码:
def saveFile():
global infile
global in_path
global txt
try:
if in_path == '':
#save as new file
in_path = asksaveasfile(initialfile='Untitled.txt', defaultextension='txt',filetypes=[("All Files","*.*"),("Text Documents","*txt")])
if in_path == "":
in_path = None
else:
#try to save file
with open(in_path, "w") as infile:
data = (txt.get(1.0, END))
infile.write(data)
#change the window title
root.title(os.path.basename(in_path))
else:
#try to save file
with open(in_path, "w") as infile:
infile.write(txt.get(1.0, END))
#change the window title
root.title(os.path.basename(in_path))
except:
pass
def saveAs():
global infile
global in_path
global txt
try:
#save as new file
in_path = asksaveasfile(initialfile='Untitled.txt', defaultextension='txt',filetypes=[("All Files","*.*"),("Text Documents","*txt")])
if in_path == " ":
in_path = None
else:
#try to save file
with open(in_path, "w") as infile:
infile.write(txt.get(1.0, END))
#change the window title
root.title(os.path.basename(in_path))
except:
pass
【问题讨论】:
-
我推荐这篇非常有用的文章:ericlippert.com/2014/03/05/how-to-debug-small-programs。
-
使用
print()来查看代码的哪一部分被执行以及变量中有什么值。它被称为“打印调试”。或者学习如何使用真正的调试器。 -
在控制台/终端中运行它时不会收到错误消息吗?
asksaveasfile不提供文件名,而是提供打开文件的处理程序。要获取文件名,您需要asksaveasfilename而不是asksaveasfile。使用print(in_path)看看你会得到什么。
标签: python file tkinter file-handling