How to delete Tkinter widgets from a window?
I have a list of tkinter
widgets that I want to change dynamically.
How to delete the widgets from the window?
You can call pack_forget
to remove a widget (if you use pack
to add it to the window).
Example:
from tkinter import *
root = Tk()
b = Button(root, text="Delete me", command=lambda: b.pack_forget())
b.pack()
root.mainloop()
If you use pack_forget
, you can later show the widget again calling pack
again. If you want to permanently delete it, call destroy
on the widget (then you won't be able to re-add it).
If you use the grid
method, you can use grid_forget
or grid_remove
to hide the widget.
One way you can do it, is to get the slaves list from the frame that needs to be cleared and destroy or "hide" them according to your needs. To get a clear frame you can do it like this:
from tkinter import *
root = Tk()
def clear():
list = root.grid_slaves()
for l in list:
l.destroy()
Label(root,text='Hello World!').grid(row=0)
Button(root,text='Clear',command=clear).grid(row=1)
root.mainloop()
You should call grid_slaves()
, pack_slaves()
or slaves()
depending on the method you used to add the widget to the frame.