【问题标题】:how to find tags near to mouse click in tkinter python gui如何在tkinter python gui中找到鼠标点击附近的标签
【发布时间】:2013-03-22 08:27:07
【问题描述】:

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

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()

谢谢

【问题讨论】:

    标签: python user-interface tkinter


    【解决方案1】:

    使用find_closestgettags

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

    顺便说一句,你必须在绑定到事件之前定义函数。

    【讨论】:

      【解决方案2】:

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

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

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

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

      (复制自effbot.org

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-31
        • 1970-01-01
        • 2012-09-12
        • 2018-07-09
        • 1970-01-01
        • 2022-01-15
        • 1970-01-01
        • 2013-03-22
        相关资源
        最近更新 更多