3

I'd like to check if a widget (such as rectangle drawn on a canvas) exists before I delete it.

Here's my problem: I have two methods that delete rectangles. One is bound to button-1 using bind (delete the rectangle when it is clicked) and the other method deletes a rectangle if it doesn't get clicked in a certain amount of time (checked using Widget.after). I would like to check if the rectangle exists in the second method because I want to count the rectangles user didn't click and the only way I can think of is check if it is already deleted. Is there a way to do this? Of course, I could set a variable inside button-1 event handler and check it from the other method. But just wanted to know if Tkinter provides method such as "item exist".

Edit : Well, I just found out one trick. If I use itemconfig on deleted widget, I get empty set. I use that value to see if a widget is already deleted or not. I'm not sure if it's an elegant way to do it though.

2 Answers 2

5

It looks to me that you could use Canvas.find_all to get a tuple of all of the items on your canvas. Then you could see if your particular item is in that tuple. e.g.:

if item in my_canvas.find_all():
   my_canvas.delete(item)
else:
   print("Item not on canvas")
Sign up to request clarification or add additional context in comments.

Comments

0

You can also unmap the widget with forget instead of destroying it so that the widget disappears but the variable name stays valid. widget.winfo_ismapped() will tell you if it is mapped.

>>> root = tk.Tk()
>>> widget = tk.Label(root, text='squeamish ossifrage')
>>> widget.winfo_ismapped()
0
>>> widget.pack()
>>> widget.winfo_ismapped()
1
>>> widget.forget()
>>> widget.winfo_ismapped()
0

There is no problem running widget.forget() on an unmapped widget so you don't even need to check its status for future statements; just run forget or run pack or overwrite the variable as needed.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.