I have a segment in my GUI that creates a varying number of labels using a for-loop. Furthermore, I have a button that’s supposed to delete all of these labels and recall the for loop with new information.
However, I can’t figure out how to make my button do that. Specifically do both of these actions together.
I have tried to delete the frame containing the labels with frame.destroy() like this:
import tkinter root = tkinter.Tk() frame = tkinter.Frame(root) frame.pack() def create(): for i in 'test': tkinter.Label(frame, text='TEST').pack() create() def command(): frame.destroy() # frame = tkinter.Frame(root) # frame.pack() create() tkinter.Button(root, text='Button', command=command).pack() root.mainloop()
That successfully deletes the labels but I can’t figure out how to create new ones.
Same thing with putting the for-loop in a class and deleting the object and creating a new one.
Is there another option than deleting each individual label? I figure that would be rather complicated as each label would need an individual variable name. Haven’t tried that yet, tho.
Thanks :)
Advertisement
Answer
You have to use global frame
in each function so that they use the same variable:
import tkinter root = tkinter.Tk() frame = tkinter.Frame(root) frame.pack() def create(): global frame for i in 'test': tkinter.Label(frame, text='TEST').pack() create() def command(): global frame frame.destroy() frame = tkinter.Frame(root) frame.pack() create() tkinter.Button(root, text='Button', command=command).pack() root.mainloop()
Since you just use .pack()
the button moves to the top after, but this should work as intended.