鼠标位置 Python Tkinter
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22925599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mouse Position Python Tkinter
提问by Kyle Pfromer
Is there a way to get the position of the mouse and set it as a var?
有没有办法获取鼠标的位置并将其设置为var?
采纳答案by unutbu
You could set up a callback to react to <Motion>
events:
您可以设置回调以对<Motion>
事件做出反应:
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()
I'm not sure what kind of variable you want. Above, I set local variables x
and y
to the mouse coordinates.
我不确定你想要什么样的变量。上面,我设置了局部变量x
和y
鼠标坐标。
If you make motion
a class method, then you could set instance attributes self.x
and self.y
to the mouse coordinates, which could then be accessible from other class methods.
如果你创建motion
一个类方法,那么你可以设置实例属性self.x
和self.y
鼠标坐标,然后可以从其他类方法访问它。
回答by Bryan Oakley
At any point in time you can use the method winfo_pointerx
and winfo_pointery
to get the x,y coordinates relative to the root window. To convert that to absolute screen coordinates you can get the winfo_pointerx
or winfo_pointery
, and from that subtract the respective winfo_rootx
or winfo_rooty
在这个时间,你可以使用方法中的任一点winfo_pointerx
,并winfo_pointery
得到x,y坐标相对于根窗口。要将其转换为绝对屏幕坐标,您可以获得winfo_pointerx
or winfo_pointery
,并从中减去相应的winfo_rootx
orwinfo_rooty
For example:
例如:
root = tk.Tk()
...
x = root.winfo_pointerx()
y = root.winfo_pointery()
abs_coord_x = root.winfo_pointerx() - root.winfo_rootx()
abs_coord_y = root.winfo_pointery() - root.winfo_rooty()
回答by JOM
Personally, I prefer to use pyautogui
, even in combination with Tkinter. It is not limited to Tkinter app, but works on the whole screen, even on dual screen configuration.
就个人而言,我更喜欢使用pyautogui
,甚至与 Tkinter 结合使用。它不仅限于 Tkinter 应用程序,还可以在整个屏幕上运行,甚至在双屏配置下也是如此。
import pyautogui
x, y = pyautogui.position()
In case you want to save various positions, add an on-click event.
I know original question is about Tkinter.
如果您想保存各种位置,请添加点击事件。
我知道最初的问题是关于 Tkinter 的。
回答by Tyler Silva
I would like to improve Bryan's answer, as that only works if you have 1 monitor, but if you have multiple monitors, it will always use your coordinates relative to your main monitor. in order to find it relative to both monitors, and get the accurate position, then use vroot
, instead of root
, like this
我想改进 Bryan 的答案,因为这仅在您有 1 台显示器时才有效,但如果您有多个显示器,它将始终使用您相对于主显示器的坐标。为了找到它相对于两台显示器,并获得准确的位置,然后使用vroot
, 而不是root
,像这样
root = tk.Tk()
...
x = root.winfo_pointerx()
y = root.winfo_pointery()
abs_coord_x = root.winfo_pointerx() - root.winfo_vrootx()
abs_coord_y = root.winfo_pointery() - root.winfo_vrooty()