编程语言
首页 > 编程语言> > 1、[python] PyMouse、PyKeyboard用python操作鼠标和键盘

1、[python] PyMouse、PyKeyboard用python操作鼠标和键盘

作者:互联网

[python] PyMouse、PyKeyboard用python操作鼠标和键盘

1、PyUserInput 简介

PyUserInput是一个使用python的跨平台的操作鼠标和键盘的模块,非常方便使用。支持的平台及依赖如下:

支持python版本:我用的是3.6.7

安装pywin32:pip install pywin32

安装pyHook:python3用pip安装会报错;需要先下载pyhook_py3k;下载地址:

下载后解压放到python安装目录的lib文件下的site-packages文件下

 python setup.py build_ext --swig=C:\Python\Python36\Tools\swigwin-3.0.12\swig.exe 执行上面代码需要先下载swig文件;下载地址:

安装PyUserInput:pip install PyUserInput

 

2、安装

直接源码安装,python3加持:

git clone https://github.com/PyUserInput/PyUserInput.git
cd PyUserInput
sudo python3 setup.py install

注: 推荐用python3

 

3、入门

实例化一个鼠标和键盘对象:

from pymouse import PyMouse
from pykeyboard import PyKeyboard

m = PyMouse()
k = PyKeyboard()

 
点击屏幕中间并输入"hello world":

x_dim, y_dim = m.screen_size()
m.click(x_dim//2, y_dim//2, 1)      #取整除 - 向下取接近除数的整数
k.type_string('Hello, World!')

 
PyKeyboard支持多种输入方法:

# pressing a key
k.press_key('H')
# which you then follow with a release of the key
k.release_key('H')
# or you can 'tap' a key which does both
k.tap_key('e')
# note that that tap_key does support a way of repeating keystrokes with a interval time between each
k.tap_key('l',n=2,interval=5)
# and you can send a string if needed too
k.type_string('o World!')

 
并且支持各种特殊的按键输入:

#Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)

k.tap_key(k.function_keys[5])  # Tap F5
k.tap_key(k.numpad_keys['Home'])  # Tap 'Home' on the numpad
k.tap_key(k.numpad_keys[5], n=3)  # Tap 5 on the numpad, thrice

 

4、PyMouse项目分析

PyUserInput开源项目维护的不太好,是将之前的PyMouse和PyKeyboard项目合到一起,而且竟然把人家之前的DEMO给删了!!!为了体验原汁原味的PyMouse我们还是单独分析吧 LINK-6

下面的一个例子展示了PyMouse的经典用法,主要用来操作鼠标 LINK-4

# import the module
from pymouse import PyMouse

# instantiate an mouse object
m = PyMouse()

# move the mouse to int x and int y (these are absolute positions)
m.move(200, 200)

# click works about the same, except for int button possible values are 1: left, 2: right, 3: middle
m.click(500, 300, 1)

# get the screen size
m.screen_size()
# (1024, 768)

# get the mouse position
m.position()
# (500, 300)

标签:tap,python,PyMouse,PyUserInput,key,PyKeyboard
来源: https://www.cnblogs.com/mashuqi/p/10408429.html