Reputation: 200
.winfo_exists() is supposed to return 1 or 0 depending on the existence of a widget
when I use .winfo_exists(), to check if a widget exists then I get the error: (Not defined)
name 'ErrorLabel' not defined
this is how I called the function:
def delete_error(self):
if self.ErrorLabel.winfo_exists() == 1: # even with 'self.' removed same error occurs
self.ErrorLabel.grid_forget()
(above is in a class)
I tried:
I don't understand why I get 'not defined' because I'm checking the existence of a object, so it doesn't have to be defined?
EDIT:
( the assignment of this variable depends if there is an error in input in the program so it doesn't always assign it,
that's why I need to check the existence of it when using grid_forget()
this is how it gets assigned:
def raise_errors(self, flag):
self.L5.grid_forget()
if flag == 1 or flag == 3 or flag == 0:
self.ErrorLabel = tk.Label(self.frame2, text="Error: Fill all the blanks !", fg='white', bg='red')
self.ErrorLabel.grid(row=7, column=0, pady=10)
elif flag == 2:
self.ErrorLabel = tk.Label(self.frame2, text="Error: check ✔️ the correct answer ", fg='white', bg='red')
self.ErrorLabel.grid(row=7, column=0, pady=10)
Upvotes: 1
Views: 384
Reputation: 15098
What you could do is set ErrorLabel
to be None
and then check if it is None
or not when calling delete_error()
, if it is None
then ignore, else find its existence.
def raise_errors(self, flag):
self.ErrorLabel = None # Set to None
self.L5.grid_forget()
if flag == 1 or flag == 3 or flag == 0:
self.ErrorLabel = tk.Label(self.frame2, text="Error: Fill all the blanks !", fg='white', bg='red')
self.ErrorLabel.grid(row=7, column=0, pady=10)
elif flag == 2:
self.ErrorLabel = tk.Label(self.frame2, text="Error: check ✔️ the correct answer ", fg='white', bg='red')
self.ErrorLabel.grid(row=7, column=0, pady=10)
Then your delete_error()
would be:
def delete_error(self):
if self.ErrorLabel is not None:
if self.ErrorLabel.winfo_exists():
self.ErrorLabel.grid_forget()
This way it checks if the widget is made and if the widget is not made, then ignores.
I don't have code here to test this with, so you should also try to define self.ErrorLabel=None
at __init__
too if first method doesn't work.
Alternatively, you could also use try
and except
to catch the error and then ignore it too:
def delete_error(self):
try:
if self.ErrorLabel.winfo_exists(): # Without setting self.ErrorLabel=None
self.ErrorLabel.grid_forget()
except NameError:
pass
Upvotes: 1