How to find out if a widget exists in Tkinter?

Now I know that you can check if a window exists:

x.winfo_exists() 

Returns a boolean value. Now I searched, but could not find exactly what I need. In particular, I need to check for the presence of my buttons, shortcuts, lists, sliders, etc.

+6
source share
2 answers

winfo_exists returns 1 if you did not destroy the widget, in which case it returns 0. This method can be called in any class of widgets, and not just in the root directory of Tk or Toplevels. In addition, you can get all widget children 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() [] 
+15
source

You can also type type type ie. (label). This can be useful to ensure not only existence, but also to find if something goes "NoneType" without errors. Type () will tell you if you have an instance or another type that can provide valuable clues as to how closely the program executes or returns elements to what you think you are asking for! Objects object.winfo_exists () and object.winfo_children are specific and will go through an error if the object is not an instance of the type.

+1
source

All Articles