Tkinter Designer

← tkinter how-to

How do I clear a window in tkinter?

There is no clear(). You destroy the widgets in the window — winfo_children() lists them, and destroy() removes each one.

for widget in root.winfo_children():
    widget.destroy()

Swapping screens is usually the better idea

Destroying everything and rebuilding is slow and loses state. If you are clearing the window to show a different screen, put each screen in its own Frame and hide one before showing the next. pack_forget() (or grid_forget()) takes a frame off screen without destroying it, so switching back is instant.

login_frame.pack_forget()
main_frame.pack(fill="both", expand=True)

Clearing one widget rather than the window

Often "clear the window" really means "empty the form". Each widget has its own way, and they differ more than you would expect:

entry.delete(0, "end")            # Entry
text.delete("1.0", "end")         # Text: line.column indices
listbox.delete(0, "end")          # Listbox
tree.delete(*tree.get_children()) # Treeview
var.set("")                       # anything using a StringVar

A gotcha with destroy in a loop

winfo_children() returns a list built at the moment you call it, so destroying as you iterate is safe here. Modifying the widget tree while iterating something else — a generator, or a list you are also appending to — is not, and it produces the classic "some widgets survived" bug.

Doing it without the lookup

Multiple screens are separate forms rather than one window being torn down and rebuilt, which is the pattern that stays maintainable. Clear Canvas empties a form while you are designing, and undo brings it back.

Lay the window out visually and read the generated Python as you go.

Open the tkinter designer →

Related questions