[Python进阶] 操纵鼠标:Pynput

6.6 操纵鼠标:Pynput

Pynput库是一个Python第三方库,用于控制和监视用户输入设备(如键盘和鼠标)。使用Pynput库可以实现以下功能:
控制键盘和鼠标:Pynput库允许模拟用户的键盘按键和鼠标点击动作。你可以编写代码来模拟按下特定的键、释放键、连续按下某个键、移动鼠标、点击或释放鼠标等。
监测键盘和鼠标事件:Pynput库提供了用于监测键盘和鼠标事件的功能。你可以编写代码来监听用户按下或释放的键、滚轮滚动、鼠标移动等等。
安装

>>> pip install pynput

6.6.1 position

返回或者设置鼠标位置。

py 复制代码
from icecream import ic
from pynput.mouse import Controller

mouse = Controller()
ic(mouse.position)  # 输出当前鼠标位置
mouse.position = 10, 20  # 设置鼠标位置
ic(mouse.position)

21:54:55|> mouse.position: (696, 585)

21:54:55|> mouse.position: (10, 20)

6.6.2 scroll(dx, dy)

鼠标滚轮滚动。注意,必须同时输入2个参数
参数:

dx: 水平方向,+向右,-向左

dy: 垂直方向,+向上,-向下

py 复制代码
from pynput.mouse import Controller

mouse = Controller()
mouse.scroll(50, 50)

6.6.3 press、release

按下或释放鼠标按键。
参数:

button:鼠标按键,左键:1,中键:2,右键:3

py 复制代码
import time
from pynput.mouse import Controller, Button

mouse = Controller()
mouse.position = (200, 200)
mouse.press(Button.left)
time.sleep(1)
mouse.release(Button.left)

6.6.4 move(dx, dy)

将鼠标移动到当前位置偏移dx,dy的位置上。

py 复制代码
from pynput.mouse import Controller
from icecream import ic

mouse = Controller()
ic(mouse.position)
mouse.position = (200, 200)
ic(mouse.position)
mouse.move(100, 300)
ic(mouse.position)

22:10:39|> mouse.position: (434, 302)

22:10:39|> mouse.position: (200, 200)

22:10:39|> mouse.position: (300, 500)

6.6.5 click(button, count=1)

按下鼠标相应的按键指定次数。
参数:

button:鼠标的按键

count:次数

py 复制代码
from pynput.mouse import Controller, Button

mouse = Controller()
mouse.position = 500, 30
mouse.click(Button.left, 2)
相关推荐
花酒锄作田32 分钟前
Pydantic校验配置文件
python
hboot1 小时前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi12 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi13 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽13 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户83580861879114 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L1 天前
LangGraph的MessageState and HumanMessage
python