【问题标题】:Tkinter: Get mouse coordinates only when mouse button is pressedTkinter:仅在按下鼠标按钮时获取鼠标坐标
【发布时间】:2021-01-05 09:30:34
【问题描述】:

我在 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)

问候!

【问题讨论】:

  • 为什么需要运动事件?信息在事件本身中。将代码复制并粘贴到您的函数中并尝试。

标签: python button events tkinter motion


【解决方案1】:

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

  • 在按钮按下/释放时设置/取消设置标志,并且在您的函数中仅在设置标志时打印坐标,
  • 绑定/取消绑定按钮按下/释放时的动作事件。

设置标志

此示例使用名为 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()

绑定/解除绑定

在本例中,我们在按下按钮时绑定 &lt;Motion&gt; 事件并在释放时取消绑定:

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

【讨论】:

  • 嗯,这确实有效!现在我在 tinkter 中创建了一个 50x50 像素的矩形,并且只想在鼠标悬停在该矩形上方时激活该绑定。有没有一种方法可以将绑定与矩形放置在框架中的信息结合起来?
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-14
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多