I am currently trying to make a simple GUI which asks a user his age and name. The names then get stored in a txt file but the GUI is working fine but the names are not getting stored in a txt file. I am getting this error -->
Exception in Tkinter callback Traceback (most recent call last): File "C:\Python39\lib\tkinter_init_.py", line 1892, in call return self.func(*args) File "c:\Users\Sumit\vs code python\projects\tkinter_course\tut_10.py", line 17, in getvals f.write(f"{uservalue.get()}") ValueError: I/O operation on closed file.
The code which I am trying to run is as follows -->
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()
CodePudding user response:
This error tells you everything you need to know.
ValueError: I/O operation on closed file.
It tried writing to a file, but the file is closed. You are prematurely closing the file before starting the main loop.
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()
The simplest solution is to only open the file when you need to write to it.
# 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()}")
Using a with
statement will automatically close the file after it finishes executing everything inside the with
. Opening a file is a quick operation so it's not necessary to open it ahead of time.