[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)
相关推荐
LXS_3571 分钟前
STL - 函数对象
开发语言·c++·算法
爱学习的阿磊4 分钟前
Python入门:从零到一的第一个程序
jvm·数据库·python
木千6 分钟前
Qt5.15.2安装MSVC2019编译器
开发语言·qt
naruto_lnq8 分钟前
编写一个Python脚本自动下载壁纸
jvm·数据库·python
仟濹10 分钟前
【Java加强】1 异常 | 打卡day1
java·开发语言·python
去往火星13 分钟前
Qt6 CMake 中引入 Qt Linguist 翻译功能
开发语言·qt
阿猿收手吧!17 分钟前
【C++】atmoic原子操作与并发安全全解析
开发语言·c++·安全
Dingdangcat8619 分钟前
基于RetinaNet的建筑表面缺陷检测与识别系统研究_2
python
zz345729811322 分钟前
C语言基础概念7
c语言·开发语言
会开花的二叉树24 分钟前
Reactor网络库的连接管理核心:Connection类
开发语言·网络·php