3

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().

pppery
  • 3,731
  • 22
  • 33
  • 46

3 Answers3

14

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()
TmZn
  • 399
  • 5
  • 16
3

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()
Mike - SMT
  • 14,784
  • 4
  • 35
  • 79
1

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.

Dr.Geek Nerd
  • 97
  • 1
  • 3
  • 11