tkinter canvas - 从事件中提取对象 ID?
tkinter canvas - extract object id from event?
有什么方法可以从事件中提取 canvas 对象的 ID?
例如,我想向 canvas 添加一个项目并绑定到它 - 但如果我的 canvas 上有多个项目,我需要区分它们他们。
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
我有一些非常 "hacky" 的方法来解决这个问题(跟踪鼠标,并向 canvas 询问离该点最近的项目)但这似乎不像 "best"方式。
有没有更好的方法?
您可以使用 find_withtag()
函数来 returns 单击的项目,如下例所示:
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()
处的简要说明
有什么方法可以从事件中提取 canvas 对象的 ID?
例如,我想向 canvas 添加一个项目并绑定到它 - 但如果我的 canvas 上有多个项目,我需要区分它们他们。
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
我有一些非常 "hacky" 的方法来解决这个问题(跟踪鼠标,并向 canvas 询问离该点最近的项目)但这似乎不像 "best"方式。
有没有更好的方法?
您可以使用 find_withtag()
函数来 returns 单击的项目,如下例所示:
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()
处的简要说明