How to check if a Widget exists?

Question:

I want to check if a button from Tkinter exists before I remove it.

To implement this, I wrote the following code:

if btn_process.winfo_exists():
    btn_process.grid_remove()

When the Button does exist, everything works fine. Although, when it doesn’t exist yet, an error message shows up in the console:

TypeError: Misc.winfo_exists() missing 1 required positional argument: ‘self’

The code is inside a function, and I also tried to declare this button as a global variable so that it exists, and put the ‘global btn_process’ at the beginning of the function, which still doesn’t work.

This error only occurs when I first check for the nonexisting button. If I create it, delete it and delete it again, there is no error.

How can I handle this error? I’m new to Python and don’t know how to interpret this error.

Asked By: VicTic

||

Answers:

The simplest and laziest way to ‘fix’ this error would be:

try:
    # [Your 'if' statement here]
except TypeError:
    pass
Answered By: Andreas Sabelfeld
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.