How to see if a widget exists in Tkinter?
22,249
winfo_exists
returns 1 unless you have destroyed the widget, in which case it returns 0. This method can be called on any widget class, not only the Tk root or Toplevels. Alternatively, you can get all the children of a widget with winfo_children
:
>>> import Tkinter as tk
>>> root = tk.Tk()
>>> label = tk.Label(root, text="Hello, world")
>>> label.winfo_exists()
1
>>> root.winfo_children()
[<Tkinter.Label instance at 0x0000000002ADC1C8>]
>>> label.destroy()
>>> label.winfo_exists()
0
>>> root.winfo_children()
[]
Author by
madprogramer
(Your about me is currently blank.) Click here to edit
Updated on March 19, 2020Comments
-
madprogramer over 4 years
Now, I know that you can check to see if a window exists by:
x.winfo_exists()
Which returns a Boolean. I have searched for this, but haven't been able to find exactly what I am looking for. More specifically I need to check the existence of my buttons, labels, list boxes, sliders etc.
-
m3nda over 8 yearsIn case that you didn't returned frame object to "root" (or directly not being created from it) you will not be able to do
label.destroy()
, but u still can search and iterate overroot.winfo_children()
list. As example,root.winfo_children()[0].destroy()
orroot.winfo_children()[1].destroy()
in case you have a Menu at top. Anyway it's more easy to create handles for every frame you use, plus insert every button/label/etc inside a main frame. -
Manish over 7 years