如何在Python中控制鼠标光标,即移动到特定位置并单击,在Windows下?
当前回答
在屏幕上随机移动鼠标
它会根据你的屏幕分辨率在屏幕上随机移动鼠标。 检查下面的代码。
使用此命令安装pip Install pyautogui。
import pyautogui
import time
import random as rnd
#calculate height and width of screen
w, h = list(pyautogui.size())[0], list(pyautogui.size())[1]
while True:
time.sleep(1)
#move mouse at random location in screen, change it to your preference
pyautogui.moveTo(rnd.randrange(0, w),
rnd.randrange(0, h))#, duration = 0.1)
其他回答
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)
尝试使用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()
如果你想移动鼠标,使用这个:
import pyautogui
pyautogui.moveTo(x,y)
如果你想点击,使用这个:
import pyautogui
pyautogui.click(x,y)
如果你没有安装pyautogui,你必须将python附加到CMD。进入CMD并输入:pip install pyautogui
这将为Python 2.x安装pyautogui。
对于Python 3。X,你可能不得不使用pip3 install pyautogui或python3 -m PIP install pyautogui。
从2022年开始,你可以使用鼠标:
import mouse
mouse.move("500", "500")
mouse.click() # default to left click
# mouse.right_click()
# mouse.double_click(button='left')
# mouse.double_click(button='right')
# mouse.press(button='left')
# mouse.release(button='left')
完整的Api文档
特性
所有鼠标设备上的全局事件钩子(捕获事件而不管 聚焦)。 监听并发送鼠标事件。 适用于Windows和Linux(需要sudo)。 纯Python,不需要编译C模块。 零依赖关系。简单的安装和部署,只需复制 文件。 Python 2 / 3 包括高级API(例如记录和播放)。 事件自动捕获在单独的线程,不阻塞主 程序。 测试并记录。
安装
Windows: pip安装鼠标 Linux: sudo pip install mouse