简体   繁体   English

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

[英]how to find tags near to mouse click in tkinter python gui

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谢谢

Use find_closest and gettags : 使用find_closestgettags

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. 顺便说一下,在将函数绑定到事件之前,必须先定义函数。

Canvas provides a bunch of find_* methods. Canvas提供了一堆find_ *方法。 Here, find_closest fit your need. 在这里, 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复制)

You can directly get the item in the canvas and find its associated tags您可以直接在canvas中获取商品,并找到其关联标签

def find_item(event):
    item = canvas.find_withtag('current')[0]
    print(canvas.gettags(item))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM