如何在Python中控制鼠标光标,即移动到特定位置并单击,在Windows下?
当前回答
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)
其他回答
接受的答案为我工作,但它是不稳定的(有时点击不会注册),所以我添加了一个额外的MOUSEEVENTF_LEFTUP。然后它就可靠地工作了
import win32api, win32con
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0)
click(10,10)
import ctypes
from time import sleep
SetCursorPos = ctypes.windll.user32.SetCursorPos
print("Woohoo!\nTake Rest!\nMouse pointer will keep moving!\n\nPress ctrl+c to stop...!")
while True:
SetCursorPos(300, 300)
sleep(2)
SetCursorPos(500, 500)
sleep(4)
非常容易 1-安装包:
pip install mouse
2-添加库到项目:
import mouse
3-举个例子:
mouse.right_click()
在这个url中描述所有你可以使用它的函数:
https://github.com/boppreh/mouse
尝试使用PyAutoGUI模块。多平台。
pip install pyautogui
所以:
import pyautogui
pyautogui.click(100, 100)
它还有其他特点:
import pyautogui
pyautogui.moveTo(100, 150)
pyautogui.moveRel(0, 10) # move mouse 10 pixels down
pyautogui.dragTo(100, 150)
pyautogui.dragRel(0, 10) # drag mouse 10 pixels down
这比浏览win32con的所有东西要容易得多。
尝试Clicknium, https://www.clicknium.com/documents/references/python/mouse/ 它可以控制鼠标和键盘,并帮助您定位web浏览器和桌面应用程序中的UI元素。
这是一个沿着圆圈移动鼠标的示例
from time import sleep
import math
from clicknium import clicknium as cc
def circle():
a,b = cc.mouse.position()
w = 20
m = (2*math.pi)/w
r = 200
while 1:
for i in range(0, w+1):
x = int(a+r*math.sin(m*i))
y = int(b+r*math.cos(m*i))
cc.mouse.move(x,y)
sleep(0.2)
if __name__ == "__main__":
circle()
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录