【发布时间】:2021-09-24 16:53:35
【问题描述】:
我需要在单击按钮时将 file_name 变量保存到文件中。请告诉我如何修复我的代码:
window = tk.Tk()
window.title("Open")
window.geometry("600x400")
window.resizable(False, False)
file_name = ""
def openu():
global file_name
if file_name == "":
file_name = tfd.askopenfilename()
with open("Filen.json", "w") as file1:
json.dump(file_name, file1, indent=2, ensure_ascii=False)
os.startfile(file_name)
else:
with open("Filen.json", "r") as file1:
json.load(file1)
os.startfile(file_name)
if btn1["text"] == "":
btn1["text"] = file_name
btn1 = tk.Button(window, text="", command=openu)
btn1.place(x = 20, y = 25)
window.mainloop()
更新: 当您单击该按钮时,程序会打开一个打开文件的对话框。一个 File.json 被创建。一切都显示出来了,但有一件事不起作用。我需要在重新启动程序时,按钮不为空。我改了代码,放了完整的。
【问题讨论】:
-
如果 file_name 为空字符串,则永远不会定义
file1。 -
@JohnGordon 请稍等,我现在将重新提出问题。
-
通过更改此代码,该错误不再发生。如果您仍然收到错误,那么您的真实代码必须与您在此处显示的不同。
-
@JohnGordon 此代码创建一个文件,打开按钮上指定的文件,但不从 File.json 加载结果。还有错误:TypeError:JSON 对象必须是 str、bytes 或 bytearray,而不是 TextIOWrapper
-
我不明白你遇到了什么问题。请说明该程序在做什么,以及它与您想要的有何不同。否则我只是猜你的意思。