python -m pip install pynput
对于每一种输入设备,它包含一个子包来控制该种设备
导入pynput控制鼠标的模块
from pynput import mouse
获取鼠标的操控对象
control = mouse.Controller()
获取当前鼠标的位置
print(control.position)
改变鼠标的位置
control.position = (100, 100)
移动鼠标的位置(x,y)
control.move(10, 10)
鼠标按键类型
按下鼠标左键
control.press(mouse.Button.left)
释放鼠标左键
control.release(mouse.Button.left)
单击鼠标左键
control.click(mouse.Button.left, 1)
双击鼠标左键
control.click(mouse.Button.left, 2)
鼠标滚轮向上滚动
control.scroll(0, -100)
鼠标滚轮向下滚动
control.scroll(0, 100)
from pynput import mouse
# 鼠标move监听
def on_move(x, y):
print(f'Current position: ({x}, {y})')
# 鼠标click监听
def on_click(x, y, button, pressed):
print(f'Click position: ({x}, {y})')
print(f'Click button: {button}')
print(f'Click state: {"Pressed" if pressed else "Release"}')
# 鼠标滚轮scroll监听
def on_scroll(x, y, dx, dy):
print(f'Scroll position: ({x}, {y})')
print(f'Scroll direction: ({dx}, {dy})')
with mouse.Listener(on_move=on_move, on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
导入pynput控制键盘的模块
from pynput import keyboard
获取按键
keyboard.Key
找到
keyboard.KeyCode.from_char'获取,特殊按键不可以,使用时会报
ArgumentError`keyboard.KeyCode.from_vk
通过键盘的映射码来获取获取键盘操作对象
control = keyboard.Controller()
模拟按键操作
按下a
键
control.press(keyboard.KeyCode.from_char(“a”))
control.press(“a”)
释放a
键
control.release(keyboard.KeyCode.from_char(“a”))
control.release(“a”)
同时按下shift
和a
键
from pynput import keyboard
control = keyboard.Controller()
with control.pressed(keyboard.Key.shift):
control.press('a')
control.release('a')
注意点
keyboard.Controller.press('a')
keyboard.Controller.release('a')
with keyboard.Controller.pressed(
keyboard.Key.ctrl,
keyboard.Key.shift,
's'):
pass
输出字符串’hello word.’
from pynput import keyboard
control = keyboard.Controller()
control.type('hello word.')
from pynput import keyboard
def on_press(key):
"""按下按键时执行。"""
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
#通过属性判断按键类型。
def on_release(key):
"""松开按键时执行。"""
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()