【问题标题】:How to display canvas coordinates when hovering cursor over canvas?将光标悬停在画布上时如何显示画布坐标?
【发布时间】:2016-01-12 07:38:07
【问题描述】:

当我将鼠标悬停在画布上时,我希望画布顶部的一些标签显示 x、y 坐标,如果我保持光标不动,这些坐标保持不变,但在我移动它时会发生变化。我该怎么做?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    您可以使用回调方法并将其绑定到Motion event

    import tkinter
    root = tkinter.Tk()
    canvas = tkinter.Canvas(root)
    canvas.pack()
    
    def moved(event):
        canvas.itemconfigure(tag, text="(%r, %r)" % (event.x, event.y))
    
    canvas.bind("<Motion>", moved)
    tag = canvas.create_text(10, 10, text="", anchor="nw")  
    
    root.mainloop()
    

    【讨论】:

      【解决方案2】:

      也可以使用&lt;Enter&gt; 事件。因此,当您在窗口之间切换时(&lt;Alt&gt;+&lt;Tab&gt; 热键),您的光标将显示正确的坐标。

      例如,您将光标放在画布上,&lt;Motion&gt; 事件将跟踪它,但是当您按 &lt;Alt&gt;+&lt;Tab&gt; 并切换到另一个窗口时,然后稍微移动光标并再次在画布上 &lt;Alt&gt;+&lt;Tab&gt; - - 光标的坐标会出错,因为&lt;Motion&gt; 事件不会跟踪窗口之间的切换。要修复它,请使用 &lt;Enter&gt; 事件。

      import tkinter
      
      root = tkinter.Tk()
      canvas = tkinter.Canvas(root)
      canvas.pack()
      
      def get_coordinates(event):
          canvas.itemconfigure(tag, text='({x}, {y})'.format(x=event.x, y=event.y))
      
      canvas.bind('<Motion>', get_coordinates)
      canvas.bind('<Enter>', get_coordinates)  # handle <Alt>+<Tab> switches between windows
      tag = canvas.create_text(10, 10, text='', anchor='nw')
      
      root.mainloop()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-26
        • 1970-01-01
        • 2014-08-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多