我目前正在嘗試制作一個簡單的 GUI,它會詢問用戶的年齡和姓名。然后將名稱存盤在 txt 檔案中,但 GUI 作業正常,但名稱未存盤在 txt 檔案中。我收到此錯誤-->
例外的Tkinter回呼回溯(最后最近通話):檔案“C:\ Python39 \ LIB \ tkinter_初始化_.py”,1892年行,在呼叫 回傳self.func(*引數)檔案“C:\用戶\薩米特\ vs 代碼 python\projects\tkinter_course\tut_10.py", line 17, in getvals f.write(f"{uservalue.get()}") ValueError: I/O operation on closed file。
我試圖運行的代碼如下-->
from tkinter import *
t = (r'C:\Users\Sumit\vs code python\projects\y.txt')
root = Tk()
root.geometry("655x333")
root.title("dance class forum")
user = Label(root, text="Name")
password = Label(root, text="Age")
user.grid()
password.grid(row=1)
f = open(t, "a")
# Variable classes in tkinter
# BooleanVar, DoubleVar, IntVar, StringVar
def getvals():
f.write(f"{uservalue.get()}")
f.write('\n')
f.write(f"{passvalue.get()}")
uservalue = StringVar()
passvalue = StringVar()
f.close()
userentry = Entry(root, textvariable = uservalue)
passentry = Entry(root, textvariable = passvalue)
userentry.grid(row=0, column=1)
passentry.grid(row=1, column=1)
Button(text="Submit", command=getvals).grid()
root.mainloop()
uj5u.com熱心網友回復:
這個錯誤告訴你你需要知道的一切。
ValueError: I/O operation on closed file.
它嘗試寫入檔案,但檔案已關閉。您在開始主回圈之前過早地關閉了檔案。
f = open(t, "a")
f.close()
# When the button is clicked and getvals is called, the file is already closed
Button(text="Submit", command=getvals).grid()
root.mainloop()
最簡單的解決方案是僅在需要寫入檔案時打開檔案。
# No longer needed
# f = open(t, "a")
# f.close()
def getvals():
with open(t, "a") as f:
f.write(f"{uservalue.get()}")
f.write('\n')
f.write(f"{passvalue.get()}")
使用with陳述句將在檔案執行完with. 打開檔案是一項快速操作,因此無需提前打開。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/394475.html
上一篇:從R到SQL重寫“模糊連接”函式
下一篇:運行注冊應用程式時,我不斷收到NameError:name'root'isnotdefinedinTkinter
