如何在Python中控制鼠标光标,即移动到特定位置并单击,在Windows下?
当前回答
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)
其他回答
查看跨平台PyMouse: https://github.com/pepijndevos/PyMouse/
你可以使用win32api或ctypes模块来使用win32api来控制鼠标或任何gui
下面是一个使用win32api控制鼠标的有趣例子:
import win32api
import time
import math
for i in range(500):
x = int(500+math.sin(math.pi*i/100)*500)
y = int(500+math.cos(i)*100)
win32api.SetCursorPos((x,y))
time.sleep(.01)
使用ctypes进行单击:
import ctypes
# see http://msdn.microsoft.com/en-us/library/ms646260(VS.85).aspx for details
ctypes.windll.user32.SetCursorPos(100, 20)
ctypes.windll.user32.mouse_event(2, 0, 0, 0,0) # left down
ctypes.windll.user32.mouse_event(4, 0, 0, 0,0) # left up
如果你想移动鼠标,使用这个:
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。
快速和肮脏的函数,在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.
在屏幕上随机移动鼠标
它会根据你的屏幕分辨率在屏幕上随机移动鼠标。 检查下面的代码。
使用此命令安装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)
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用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中获得所有直接子目录