13

Now, I know that you can check to see if a window exists by:

x.winfo_exists()

which returns a Boolean. More exactly, I need to check the existence of my buttons, labels, list boxes, sliders etc. Then what?

2
  • 1
    Your question is unclear. You say you know you can call winfo_exists to determine if a widget exists, but you don't know how to tell if your widgets exist? Mar 9, 2013 at 17:43
  • NO, to see if a window exists. I didn't know it also worked for widgets until I got this answer. Thanks by the way. Mar 10, 2013 at 6:09

2 Answers 2

27

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()
[]
1
  • 1
    In 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 over root.winfo_children() list. As example, root.winfo_children()[0].destroy() or root.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.
    – m3nda
    Nov 8, 2015 at 20:11
0

You can also print the type i.e.. type(label). This can be helpful to provide not only existence, but also find if anything is coming up 'NoneType' without an error. The type() will tell you if you have an instance, or other type that can provide valuable clues as to how close the program is performing or returning items to what you think you are asking! The object.winfo_exists() and object.winfo_children is specific, and will throw an error if the object is not a type 'instance'.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.