[英]Tkinter: Get mouse coordinates only when mouse button is pressed
I have a rather specific question in Python.我在 Python 中有一个相当具体的问题。
I know the solution for constantly recieving the mouse coordinates on a frame in Tkinter:我知道在 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()
My question is now combining a button pressed and the motion event.我的问题现在结合按下按钮和动作事件。 In a nutshell: I want the mouse coordinates only when the button is pressed, not when it's released or not pressed.
简而言之:我只在按下按钮时才想要鼠标坐标,而不是在释放或未按下时。
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)
Regards!问候!
There are at least two very simple solutions:至少有两个非常简单的解决方案:
This example uses a flag named do_capture
which is set to True
with a button press and set to False
on a button release:此示例使用一个名为旗
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()
In this example, we bind the <Motion>
event on the press of a button and unbind it on the release:在这个例子中,我们在按下按钮时绑定
<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()
If you don't want to store the mouse position in the motion callback and then read it again in the button's callback, you can use winfo_pointer()
to get the absolute pointer position on your screen and subtract the window position winfo_root()
to get the pointer position relative to the window.如果您不想在动作回调中存储鼠标位置,然后在按钮的回调中再次读取它,您可以使用
winfo_pointer()
获取屏幕上的绝对指针位置并减去窗口位置winfo_root()
得到相对于窗口的指针位置。
Of course, you would need to catch pointer positions outside the window yourself.当然,您需要自己捕捉窗口外的指针位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.