如何在Python中控制鼠标光标,即移动到特定位置并单击,在Windows下?
当前回答
如果你需要玩游戏的话。正如本文https://www.learncodebygaming.com/blog/pyautogui-not-working-use-directinput中所解释的,像《我的世界》或《堡垒之夜》等游戏都有自己的鼠标/键盘事件注册方式。控制鼠标和键盘事件的方法是使用全新的PyDirectInput库。他们的github知识库是https://github.com/learncodebygaming/pydirectinput,有很多很棒的信息。 下面是一个快速的代码,执行鼠标循环,点击:
import pydirectinput # pip install pydirectinput
pydirectinput.moveTo(0, 500)
pydirectinput.click()
其他回答
快速和肮脏的函数,在Windows 7上使用ctypes库左键点击。无需下载。
import ctypes
SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event
def left_click(x, y, clicks=1):
SetCursorPos(x, y)
for i in xrange(clicks):
mouse_event(2, 0, 0, 0, 0)
mouse_event(4, 0, 0, 0, 0)
left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.
Linux
from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
d.sync()
来源:Python鼠标移动5行代码(仅适用于Linux)。
Pynput是我发现的最好的解决方案,无论是Windows还是Mac。超级容易编程,工作得非常好。
例如,
from pynput.mouse import Button, Controller
mouse = Controller()
# Read pointer position
print('The current pointer position is {0}'.format(
mouse.position))
# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
mouse.position))
# Move pointer relative to current position
mouse.move(5, -5)
# Press and release
mouse.press(Button.left)
mouse.release(Button.left)
# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)
# Scroll two steps down
mouse.scroll(0, 2)
另一种选择是使用跨平台AutoPy包。这个包有两个不同的选项来移动鼠标:
这段代码片段将立即将光标移动到(200,200)位置:
import autopy
autopy.mouse.move(200,200)
如果你想让光标在屏幕上移动到一个给定的位置,你可以使用smooth_move命令:
import autopy
autopy.mouse.smooth_move(200,200)
查看跨平台PyMouse: https://github.com/pepijndevos/PyMouse/
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录