[python]python监听、操作键盘鼠标库pynput详细教程
pynput
库提供了控制和监听键盘与鼠标的功能。以下是使用 pynput
库的基本示例。
监听键盘事件:
from pynput import keyboard
def on_press(key):
try:
print(f"按下键: {key.char}")
except AttributeError:
print(f"按下键: {key}")
def on_release(key):
print(f"释放键: {key}")
if key == keyboard.Key.esc:
return False
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
listener.join()
监听鼠标事件:
from pynput import mouse
def on_click(x, y, button, pressed):
if pressed:
print(f"点击位置: ({x}, {y}) 按钮: {button}")
else:
print(f"释放位置: ({x}, {y}) 按钮: {button}")
def on_scroll(x, y, dx, dy):
print(f"滚动位置: ({x}, {y}) 偏移: ({dx}, {dy})")
with mouse.Listener(on_click=on_click, on_scroll=on_scroll) as listener:
listener.join()
控制鼠标移动和点击:
from pynput.mouse import Button, Controller
mouse = Controller()
# 移动鼠标到屏幕中心
mouse.position = (100, 100)
# 点击左键
mouse.press(Button.left)
mouse.release(Button.left)
# 点击右键
mouse.press(Button.right)
mouse.release(Button.right)
# 移动鼠标
mouse.move(100, 0)
控制键盘输入:
from pynput.keyboard import Key, Controller
keyboard = Controller()
# 按下并释放 'a' 键
keyboard.press('a')
keyboard.release('a')
# 输入 'Hello World!'
keyboard.type('Hello World!')
以上代码提供了使用 pynput
进行键盘和鼠标监听以及模拟输入的基本示例。
评论已关闭