mouse:顾名思义,是控制鼠标的模块,本篇不打算介绍,有兴趣可以看官网mouse
keyboard:同样,是控制键盘的模块,可以完全控制键盘,本篇不打算介绍,源码很少,有兴趣可以看官网keyboard
一.介绍
pynput这个库让你可以控制和监控输入设备,它包含一个子模块来控制和监控该种输入设备:
-
pynput.mouse:包含控制和监控鼠标或者触摸板的类。
-
pynput.keyboard:包含控制和监控键盘的类。
两个子模块的结构,两者结构相同
二.实例
2.1 pynput.mouse
from pynput.mouse import Button, Controller,Listener # Controller类 m = Controller() print('鼠标的坐标:{0}'.format(m.position)) m.position = (500, 200) print('设置鼠标的坐标:{0}'.format(m.position)) # 相对于当前位置移动鼠标 m.move(m.position[0],m.position[1]) # 按下鼠标左键以及松开鼠标左键,按下并不是点击 m.press(Button.left) m.release(Button.left) #双击鼠标右键 m.click(Button.right, 2) #滚动 m.scroll(0, 2) # Listener类,监听鼠标事件 def on_move(x, y): print('移动到了:{0}'.format((x, y))) def on_click(x, y, button, pressed): print('{0} at {1}'.format('按下' if pressed else '松开',(x, y))) if not pressed: # 停止监听 return False # 监听滚动事件 def on_scroll(x, y, dx, dy): print('滚动到: {0}'.format((x, y))) with Listener(on_move=on_move,on_click=on_click,on_scroll=on_scroll) as listener: listener.join()