【发布时间】:2016-01-12 07:38:07
【问题描述】:
当我将鼠标悬停在画布上时,我希望画布顶部的一些标签显示 x、y 坐标,如果我保持光标不动,这些坐标保持不变,但在我移动它时会发生变化。我该怎么做?
【问题讨论】:
当我将鼠标悬停在画布上时,我希望画布顶部的一些标签显示 x、y 坐标,如果我保持光标不动,这些坐标保持不变,但在我移动它时会发生变化。我该怎么做?
【问题讨论】:
您可以使用回调方法并将其绑定到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()
【讨论】:
也可以使用<Enter> 事件。因此,当您在窗口之间切换时(<Alt>+<Tab> 热键),您的光标将显示正确的坐标。
例如,您将光标放在画布上,<Motion> 事件将跟踪它,但是当您按 <Alt>+<Tab> 并切换到另一个窗口时,然后稍微移动光标并再次在画布上 <Alt>+<Tab> - - 光标的坐标会出错,因为<Motion> 事件不会跟踪窗口之间的切换。要修复它,请使用 <Enter> 事件。
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()
【讨论】: