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

问题描述

我在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,event.y
    print('{},y))

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

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

root.mainloop()
,

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

当然,您需要自己在窗口外部捕获指针位置。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...