2

I am currectly building a Tkinter GUI using Python, and I want to see how I can remove all elements, creating a blank clean slate. I tried .destroy(), but that completely exits out the window. How do I do this?

Example code:

import tkinter as tk

root = tk.Tk()
mylabel = tk.Label(root, text='I want this to be removed')
mylabel.pack()
#I want to remove the mylabel Label.
  • You used pack so you can use unpack to remove the elements. Read this https://stackoverflow.com/questions/12364981/how-to-delete-tkinter-widgets-from-a-window – Harsh Dec 03 '20 at 04:30

1 Answers1

2

You can either remove or destroy all children of the root iteratively (eg: for child in root.winfo_children(): child.destroy()), or you can create a single frame directly in the root and make all other widgets children of that frame, and then just remove or delete the frame.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • I'm new to this and I even created an alt to avoid downvotes on my main acc :(, but does children refer to each object (label, button, etc)? – dinosauce34 Dec 03 '20 at 04:31
  • 1
    @dinosauce34: you should not be creating more than one account. If you don't want downvotes, write better questions. Yes, "children" refers to the individual widgets. – Bryan Oakley Dec 03 '20 at 05:20
  • Is there a way to do this while the GUI is running? When I run the for loop while the GUI is running, I get this error: for child in root.winfo_children: TypeError: 'method' object is not iterable – dinosauce34 Dec 04 '20 at 04:14
  • 2
    @dinosauce34 _"Is there a way to do this while the GUI is running?"_ - well, you certainly can't do it if it's _not_ running. You have to _call_ the method - `root.winfo_children()`. – Bryan Oakley Dec 04 '20 at 04:30