I want to enter an item into the entry box press a button and add the item to the list changing the list permanently, however I cannot seem to make a permanent change to the list. The program always returns "[]" and never the updated list. Is there a way I can do this?
I have tested and there are no issues involving extracting text from the entry box and adding It to the list. The only problem is making the change permanent.
here is the code:
from tkinter import *
window = Tk()
names = []
ent = Entry(window)
ent.pack()
def change():
names.append(ent.get())
btn = Button (window, command = change )
btn.pack()
print(names)
window.mainloop()
why is the response always "[]" and not the updated list
CodePudding user response:
It is printing an empty list because the list is empty. You are not printing after appending
from tkinter import *
window = Tk()
names = []
ent = Entry(window) ent.pack()
def change():
names.append(ent.get())
print(names)
btn = Button (window, command = change ) btn.pack()
#print(names)
window.mainloop()
CodePudding user response:
While mapperx's answer is correct, I think what you're trying to do is to persist the list, so that when you close the program and open it again, the names are still there. If this is what you intend, you need to store the list (or its content) into a file before closing the program.
You can do this using pickle.
from tkinter import *
import pickle
window = Tk()
# Create list from file (if no file exists, create empty list)
try:
with open('names.pickle', 'rb') as f: names = pickle.load(f)
except: names = []
ent = Entry(window)
ent.pack()
def change():
names.append(ent.get())
btn = Button (window, command = change )
btn.pack()
print(names)
def onClose():
with open('names.pickle', 'wb') as f: pickle.dump(names, f) # Store (persist) the list
window.destroy()
# This will call "onClose" before closing the window
window.protocol("WM_DELETE_WINDOW", onClose)
window.mainloop()
You can change names.pickle
to any filename you want