是否可以使用标准的Python库在Windows中获取整体鼠标位置?
是否可以使用标准的Python库在Windows中获取整体鼠标位置?
使用标准的ctypes库,这应该可以获取当前屏幕上鼠标坐标,无需任何第三方模块:
使用标准的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)
我应该提到这段代码是从一个例子中获得的,可以在这里找到。 因此,这个解决方案归功于Nullege.com。
win32gui.GetCursorPos(point)
这将检索光标在屏幕坐标中的位置 - point = (x,y)
flags, hcursor, (x,y) = win32gui.GetCursorInfo()
检索有关全局光标的信息。
链接:
我假设您将使用Python Win32 API绑定或pywin32。
在标准的Python库中,您将找不到这样的函数,这个函数是专门针对Windows开发的。但是,如果您使用ActiveState Python,或者只需将win32api
模块安装到标准的Python Windows安装上,您就可以使用:
x, y = win32api.GetCursorPos()
pywin32
(不是pypiwin32)。 - Christoph Rackwitz使用pyautogui
安装
pip install pyautogui
查找鼠标指针位置的方法
import pyautogui
print(pyautogui.position())
这将给出鼠标指针所在的像素位置。
这是可以做到的,而且并不会太混乱!只需使用:
from ctypes import windll, wintypes, byref
def get_cursor_pos():
cursor = wintypes.POINT()
windll.user32.GetCursorPos(byref(cursor))
return (cursor.x, cursor.y)
pyautogui
的答案让我好奇这个模块是如何实现的,所以我查看了一下,下面是实现方式。while(1): print('{}\t\t\r'.format(get_cursor_pos()), end='')
- not2qubitself.winfo_pointerxy()
p=Tkinter.Tk()
,最后得到 p.winfo_pointerxy()
,它将返回当前光标位置的元组 :) - Waffle's Crazy Peanut对于使用本地库的Mac:
import Quartz as q
q.NSEvent.mouseLocation()
#x and y individually
q.NSEvent.mouseLocation().x
q.NSEvent.mouseLocation().y
python3 -m pip install -U pyobjc-framework-Quartz
这个问题指定了Windows,但很多Mac用户因为标题而来到这里。
安装 Tkinter
。我已经包含了 win32api 作为仅适用于 Windows 的解决方案。
#!/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())
我知道这是一个旧线程,但一直在努力弄清如何仅使用Python标准库完成此操作。
我认为下面的代码可以用于获取Windows终端中的光标位置:
import sys
import msvcrt
print('ABCDEF',end='')
sys.stdout.write("\x1b[6n")
sys.stdout.flush()
buffer = bytes()
while msvcrt.kbhit():
buffer += msvcrt.getch()
hex_loc = buffer.decode()
hex_loc = hex_loc.replace('\x1b[','').replace('R','')
token = hex_loc.split(';')
print(f' Row: {token[0]} Col: {token[1]}')