Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tkinter canvas - extract object id from event?

Is there a way I can extract the canvas object's id from an event?

For example, I'd like to add an item to a canvas, and bind to it - but if I have multiple items of them on my canvas, I need to distinguish between them.

def add_canvas_item(self,x,y):
    canvas_item_id = self.canvas.create_oval(x-50,y-50,x+50,y+50, fill='green')
    self.canvas.tag_bind(canvas_item_id ,"<ButtonPress-1>",self.stateClicked)

def itemClicked(self,event):
    print("Item XYZ Clicked!") <- Where XYZ is the ID of the item

I have some very "hacky" ways around this (keep track of the mouse, and ask the canvas for the nearest item to that point) but that doesn't seem like the "best" way.

Is there a better way?

like image 541
trayres Avatar asked Sep 12 '25 06:09

trayres


1 Answers

You can use the find_withtag() function which returns the clicked item as in the example below:

from tkinter import *

root = Tk()
canvas = Canvas(root)
canvas.pack()

def itemClicked(event):
    canvas_item_id = event.widget.find_withtag('current')[0]
    print('Item', canvas_item_id, 'Clicked!')

def add_canvas_item(x,y):
    canvas_item_id = canvas.create_oval(x-50,y-50,x+50,y+50, fill='green')
    canvas.tag_bind(canvas_item_id ,'<ButtonPress-1>', itemClicked)

add_canvas_item(100,100)    # Test item 1
add_canvas_item(250,150)    # Test item 2

root.mainloop()

Brief description at Tracking Mouse Actions for Many Canvas Objects

like image 82
figbeam Avatar answered Sep 13 '25 20:09

figbeam