如何在tkinter python gui中找到鼠标点击附近的标签

时间:2022-11-05 13:49:19

How can i identify a tag near to mouse click. here my definition "identify" should identify tag very near to mouse click.

如何识别鼠标点击附近的标签。在这里我的定义“识别”应该识别非常接近鼠标点击的标签。

from Tkinter import *
root = Tk()
f=Frame(root)
f.grid()
w=Canvas(f)
line1=w.create_line(50,50,150,150, width=5, tags="line1")
line2=w.create_line(100,100,100,350, width=3, tags="line2")
line3=w.create_line(150,150,150,450, width=3, tags="lines")
w.grid(row=0, column=0)
w.bind("<Button-1>", identify)
def identify(event): ## this should identify the tag near to click

u=Frame(f)
u.grid(row=0, column=1)
root.mainloop()

Thanks

谢谢

2 个解决方案

#1


5  

Use find_closest and gettags:

使用find_closest和gettags:

def identify(event):
    item = w.find_closest(event.x, event.y)[0]
    tags = w.gettags(item)
    print tags

By the way, you have to define the function before you bind it to the event.

顺便说一下,在将函数绑定到事件之前,必须先定义函数。

#2


3  

Canvas provides a bunch of find_* methods. Here, find_closest fit your need.

Canvas提供了一堆find_ *方法。在这里,find_closest符合您的需求。

def identify(event):
    closest = w.find_closest(event.x,event.y)[0]

Note that if you change the viewport of the canvas (pan, zoom...), you will have to convert from event coordinate to canvas coordinate

请注意,如果更改画布的视口(平移,缩放...),则必须从事件坐标转换为画布坐标

def callback(event):
    canvas = event.widget
    x = canvas.canvasx(event.x)
    y = canvas.canvasy(event.y)
    print canvas.find_closest(x, y)

(copied from effbot.org)

(从effbot.org复制)

#1


5  

Use find_closest and gettags:

使用find_closest和gettags:

def identify(event):
    item = w.find_closest(event.x, event.y)[0]
    tags = w.gettags(item)
    print tags

By the way, you have to define the function before you bind it to the event.

顺便说一下,在将函数绑定到事件之前,必须先定义函数。

#2


3  

Canvas provides a bunch of find_* methods. Here, find_closest fit your need.

Canvas提供了一堆find_ *方法。在这里,find_closest符合您的需求。

def identify(event):
    closest = w.find_closest(event.x,event.y)[0]

Note that if you change the viewport of the canvas (pan, zoom...), you will have to convert from event coordinate to canvas coordinate

请注意,如果更改画布的视口(平移,缩放...),则必须从事件坐标转换为画布坐标

def callback(event):
    canvas = event.widget
    x = canvas.canvasx(event.x)
    y = canvas.canvasy(event.y)
    print canvas.find_closest(x, y)

(copied from effbot.org)

(从effbot.org复制)