I'm trying to clear a tkinter window completely. However, I need a way to clear every widget on the window all at once without using pack.forget()
.

- 3,731
- 22
- 33
- 46

- 57
- 1
- 1
- 6
-
What do you mean by `without using pack_forget.`? – xmcp Aug 27 '17 at 14:15
-
3Put them all in a separate frame and add/remove the frame as needed? – chepner Aug 27 '17 at 14:38
-
https://stackoverflow.com/q/15995783/7432 – Bryan Oakley Aug 28 '17 at 13:02
3 Answers
You could use a simple recursive loop to list all the children wigets of your main window :
def all_children (window) :
_list = window.winfo_children()
for item in _list :
if item.winfo_children() :
_list.extend(item.winfo_children())
return _list
Then just use this list :
widget_list = all_children(window)
for item in widget_list:
item.pack_forget()

- 399
- 5
- 16
What you need to do is set a frame to your main window and place everything that is to be cleared out at some point inside that frame. Then you simply do frame_name.destroy()
The following example has a button that creates a frame with several label widgets and a button.
The button calls a method that will destroy the frame and everything in it.
Then you can create the frame again with the first button.
Let me know if you have any question:
import tkinter as tk
class ExampleApp(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.some_frame = None
tk.Button(self.master, text="Create new frame with widgets!", command = self.create_stuff).pack()
def create_stuff(self):
if self.some_frame == None:
self.some_frame = tk.Frame(self.master)
self.some_frame.pack()
for i in range(5):
tk.Label(self.some_frame, text = "This is label {}!".format(i+1)).pack()
tk.Button(self.some_frame, text="Destroy all widgets in this frame!",
command= self.destroy_some_frame).pack()
def destroy_some_frame(self):
self.some_frame.destroy()
self.some_frame = None
root = tk.Tk()
my_example = ExampleApp(root)
root.mainloop()

- 14,784
- 4
- 35
- 79
You can use destroy method for each widget for example if it's a button you write btn1.destroy() and do it for all widgets. The forget method isn't recommended for it only remove the widgets from appearance.

- 97
- 1
- 3
- 11