在 Python 中获取光标位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3698635/
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
Getting cursor position in Python
提问by rectangletangle
Is it possible to get the overall cursor position in Windows using the standard Python libraries?
是否可以使用标准 Python 库在 Windows 中获取整体光标位置?
采纳答案by pyfunc
win32gui.GetCursorPos(point)
This retrieves the cursor's position, in screen coordinates - point = (x,y)
这将检索光标的位置,在屏幕坐标中 - point = (x,y)
flags, hcursor, (x,y) = win32gui.GetCursorInfo()
Retrieves information about the global cursor.
检索有关全局游标的信息。
Links:
链接:
- http://msdn.microsoft.com/en-us/library/ms648389(VS.85).aspx
- http://msdn.microsoft.com/en-us/library/ms648390(VS.85).aspx
- http://msdn.microsoft.com/en-us/library/ms648389(VS.85).aspx
- http://msdn.microsoft.com/en-us/library/ms648390(VS.85).aspx
I am assuming that you would be using python win32 API bindings or pywin32.
我假设您将使用 python win32 API 绑定或 pywin32。
回答by Micha? Niklas
You will not find such function in standard Python libraries, while this function is Windows specific. However if you use ActiveState Python, or just install win32apimodule to standard Python Windows installation you can use:
您不会在标准 Python 库中找到此类函数,而此函数是特定于 Windows 的。但是,如果您使用 ActiveState Python,或者只是将win32api模块安装到标准 Python Windows 安装中,您可以使用:
x, y = win32api.GetCursorPos()
回答by rectangletangle
I found a way to do it that doesn't depend on non-standard libraries!
我找到了一种不依赖于非标准库的方法!
Found this in Tkinter
在 Tkinter 中找到了这个
self.winfo_pointerxy()
回答by Micrified
Using the standard ctypes library, this should yield the current on screen mouse coordinates without any third party modules:
使用标准 ctypes 库,这应该在没有任何第三方模块的情况下产生当前的屏幕鼠标坐标:
from ctypes import windll, Structure, c_long, byref
class POINT(Structure):
_fields_ = [("x", c_long), ("y", c_long)]
def queryMousePosition():
pt = POINT()
windll.user32.GetCursorPos(byref(pt))
return { "x": pt.x, "y": pt.y}
pos = queryMousePosition()
print(pos)
I should mention that this code was taken from an example found hereSo credit goes to Nullege.com for this solution.
回答by Martin Thoma
Prerequisites
先决条件
Install Tkinter. I've included the win32api for as a Windows-only solution.
安装Tkinter. 我已将 win32api 作为仅适用于 Windows 的解决方案。
Script
脚本
#!/usr/bin/env python
"""Get the current mouse position."""
import logging
import sys
logging.basicConfig(format='%(asctime)s %(levelname)s %(message)s',
level=logging.DEBUG,
stream=sys.stdout)
def get_mouse_position():
"""
Get the current position of the mouse.
Returns
-------
dict :
With keys 'x' and 'y'
"""
mouse_position = None
import sys
if sys.platform in ['linux', 'linux2']:
pass
elif sys.platform == 'Windows':
try:
import win32api
except ImportError:
logging.info("win32api not installed")
win32api = None
if win32api is not None:
x, y = win32api.GetCursorPos()
mouse_position = {'x': x, 'y': y}
elif sys.platform == 'Mac':
pass
else:
try:
import Tkinter # Tkinter could be supported by all systems
except ImportError:
logging.info("Tkinter not installed")
Tkinter = None
if Tkinter is not None:
p = Tkinter.Tk()
x, y = p.winfo_pointerxy()
mouse_position = {'x': x, 'y': y}
print("sys.platform={platform} is unknown. Please report."
.format(platform=sys.platform))
print(sys.version)
return mouse_position
print(get_mouse_position())
回答by Michael Wang
Use pygame
使用 pygame
import pygame
mouse_pos = pygame.mouse.get_pos()
This returns the x and y position of the mouse.
这将返回鼠标的 x 和 y 位置。
See this website: https://www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos
请参阅此网站:https: //www.pygame.org/docs/ref/mouse.html#pygame.mouse.set_pos
回答by jturi
sudo add-apt-repository ppa:deadsnakes
sudo apt-get update
sudo apt-get install python3.5 python3.5-tk
# or 2.7, 3.6 etc
# sudo apt-get install python2.7 python2.7-tk
# mouse_position.py
import Tkinter
p=Tkinter.Tk()
print(p.winfo_pointerxy()
Or with one-liner from the command line:
或者使用命令行中的单行:
python -c "import Tkinter; p=Tkinter.Tk(); print(p.winfo_pointerxy())"
(1377, 379)
回答by Abhinav
Using pyautogui
使用 pyautogui
To install
安装
pip install pyautogui
pip install pyautogui
and to find the location of the mouse pointer
并找到鼠标指针的位置
import pyautogui
print(pyautogui.position())
This will give the pixel location to which mouse pointer is at.
这将给出鼠标指针所在的像素位置。

