7

I have a few different object tags within a tkinter canvas. I would like the user to be able to delete the current object under the mouse cursor with the tag "token".

I do not want all objects with the tag "token" to be deleted, only the one under the mouse cursor. I would like any object with the tag "token" to be able to be deleted. I want to prohibit deletion of objects with tags "line". I've tried:

self.canvas.delete("current")

But this allows me to delete anything under my mouse cursor (including the line object). When I tried

self.canvas.delete("token")

This allowed me to delete all items with the tag "token" all at once. Here is an excerpt of the definitions for my line object, "token" objects, and my delete function:

 # create static line
    self.canvas.create_line(50,250,200,250, width=7, fill="grey", tags="line")

 #Create oval
 myoval = self.canvas.create_oval(x0,y0,x1,y1, width=10, outline="black", fill="black",
                                  tags="token")


 def on_button_press_deleteoval(self,event):
    '''Delete oval with double button 1 click.'''
    self.canvas.delete("current")
martineau
  • 119,623
  • 25
  • 170
  • 301
user1332577
  • 362
  • 5
  • 17
  • if i recall correctly, all widgets have id's maybe you can delete by id? i think you would have to capture the id of all the widgets with the corresponding tag in order to delete them – glls May 23 '16 at 00:25
  • Yes, I"ve tried this with the self.canvas.find_withtag("token") or self.canvas.gettags("token") option but I still end up only being able to delete all of them at the same time or anything under my cursor. I'm obviously implementing it wrong, but not sure of how to change the approach so it will work. – user1332577 May 23 '16 at 00:50

1 Answers1

11

You can either take the long way:

if 'token' in canvas.gettags(canvas.find_withtag('current')):
    canvas.delete('current')

or use a shortcut:

canvas.delete('current&&token') #logical operator in tag search expression

# && = AND, || = OR, ! = NOT
Billal Begueradj
  • 20,717
  • 43
  • 112
  • 130
Oblivion
  • 1,669
  • 14
  • 14
  • Thank you so much! Works like a charm. I can't believe I didn't think of that. I took the shortcut, but it's good to know that other options exist. – user1332577 May 25 '16 at 00:41