繁体   English   中英

Tkinter:仅在按下鼠标按钮时获取鼠标坐标

[英]Tkinter: Get mouse coordinates only when mouse button is pressed

我在 Python 中有一个相当具体的问题。

我知道在 Tkinter 的框架上不断接收鼠标坐标的解决方案:

import Tkinter as tk
root = tk.Tk()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

root.bind('<Motion>', motion)
root.mainloop()

我的问题现在结合按下按钮和动作事件。 简而言之:我只在按下按钮时才想要鼠标坐标,而不是在释放或未按下时。

def ButtonPress(event):
    #This is the part, where I can't figure out, how to proceed.
    #How can I call the motion event from here.


Bt = Button(root, text='Press for coordinates!')
Bt.bind('<ButtonPress>', ButtonPress)

问候!

至少有两个非常简单的解决方案:

  • 在按钮按下/释放时设置/取消设置标志,如果设置了标志,则在您的函数中仅打印坐标,
  • 绑定/取消绑定按钮按下/释放时的运动事件。

设置标志

此示例使用一个名为旗do_capture被设置为True按下一个按钮,并设置为False上的按钮释放:

import Tkinter as tk
root = tk.Tk()

def motion(event):
    if do_capture:
        x, y = event.x, event.y
        print('{}, {}'.format(x, y))

def capture(flag):
    global do_capture
    do_capture = flag

root.bind('<Motion>', motion)
root.bind("<ButtonPress-1>", lambda event: capture(True))
root.bind("<ButtonRelease-1>", lambda event: capture(False))

capture(False)

root.mainloop()

绑定/解绑

在这个例子中,我们在按下按钮时绑定<Motion>事件并在释放时解除绑定:

import Tkinter as tk
root = tk.Tk()

def motion(event):
    x, y = event.x, event.y
    print('{}, {}'.format(x, y))

def capture(flag):
    if flag:
        root.bind('<Motion>', motion)
    else:
        root.unbind('<Motion>')

root.bind("<ButtonPress-1>", lambda event: capture(True))
root.bind("<ButtonRelease-1>", lambda event: capture(False))

root.mainloop()

如果您不想在动作回调中存储鼠标位置,然后在按钮的回调中再次读取它,您可以使用winfo_pointer()获取屏幕上的绝对指针位置并减去窗口位置winfo_root()得到相对于窗口的指针位置。

当然,您需要自己捕捉窗口外的指针位置。

暂无
暂无

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

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