【322】python控制键盘鼠标:pynput

参考:python实战===python控制键盘鼠标:pynput

参考:[Python Study Notes]pynput实现对鼠标控制

参考:pynput doc

参考:pynput Package Documentation


Python控制键盘鼠标:pynput
地址:pynput - PyPI

这个库让你可以控制和监控输入设备。
对于每一种输入设备,它包含一个子包来控制和监控该种输入设备:

  • pynput.mouse:包含控制和监控鼠标或者触摸板的类。
  • pynput.keyboard:包含控制和监控键盘的类。

基本用法介绍:

from  pynput.mouse import Button, Controller
import time 

# 获取鼠标位置
mouse = Controller()
print(mouse.position)
time.sleep(3)
print('The current pointer position is {0}'.format(mouse.position))

# 设置鼠标位置
mouse.position = (277, 645)
print('now we have moved it to {0}'.format(mouse.position))

# 鼠标移动(x,y)个距离
mouse.move(5, -5)
print(mouse.position)

# 鼠标单击与释放
mouse.press(Button.left)
mouse.release(Button.left)

# 左键单击
mouse.click(Button.left,1)

# 右键单击
mouse.click(Button.right,1)
 
# 左键双击
mouse.click(Button.left,2)

# 鼠标滚动(x,y)  x代表左右移动,y代表上下移动
# X:正值代表从右向左   Y:正值代表向上移动,负值代表向下移动
mouse.scroll(0, 100)

监控鼠标事件 :略

键盘输入用法:

from pynput.keyboard import Key, Controller

keyboard = Controller()

#Press and release space
keyboard.press(Key.space)
keyboard.release(Key.space)

#Type a lower case A ;this will work even if no key on the physical keyboard  is labelled 'A'
keyboard.press('a')
keyboard.release('a')

#Type two  upper case As
keyboard.press('A')
keyboard.release('A')
# or 
with keyboard.pressed(Key.shift):
    keyboard.press('a')
    keyboard.release('a')

#type 'hello world '  using the shortcut type  method
keyboard.type('hello world')

综合使用:

import pynput
from pynput.mouse import Button
from pynput.keyboard import Key
mouse = pynput.mouse.Controller()
keyboard = pynput.keyboard.Controller()
...
原文地址:https://www.cnblogs.com/alex-bn-lee/p/9208931.html