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 :)
CodePudding user response:
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.
CodePudding user response:
Try this method:
import tkinter as tk
class Testing:
def __init__(self):
self.root = tk.Tk()
self.flag = True
self.create()
self.com_button()
self.root.mainloop()
def create(self):
self.frame = tk.Frame(self.root)
for n, i in enumerate('test'):
tk.Label(self.frame, text='TEST').grid(row=n, column=0)
self.frame.grid(row=0, column=0)
def command(self):
if self.flag:
self.frame.grid_forget()
self.flag = False
else:
self.create()
self.flag = True
def com_button(self):
tk.Button(self.root, text='Button', command=self.command).grid(row=1, column=0)
if __name__=='__main__':
Testing()
