How to see if a widget exists in Tkinter?

前端 未结 2 1729
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 07:51

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\

相关标签:
2条回答
  • 2021-01-02 08:21

    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'.

    0 讨论(0)
  • 2021-01-02 08:31

    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()
    []
    
    0 讨论(0)
提交回复
热议问题