目录
python 监听鼠标和键盘
开始前安装 pynput
pip install pynput
from pynput import keyboard, mouse
# 监听鼠标点击事件
def on_click(x, y, button, pressed):
if pressed and button == mouse.Button.left:
print("鼠标左键被按下")
elif pressed and button == mouse.Button.right:
print("鼠标右键被按下")
# 监听鼠标滚轮事件
def on_scroll(x, y, dx, dy):
if dy < 0:
print("鼠标向下滚动")
elif dy > 0:
print("鼠标向上滚动")
# 监听键盘按下事件
def on_press(key):
try:
print("按键 {0} 被按下".format(key.char))
except AttributeError:
print("特殊按键 {0} 被按下".format(key))
# 创建鼠标监听器
mouse_listener = mouse.Listener(on_click=on_click, on_scroll=on_scroll)
mouse_listener.start()
# 创建键盘监听器
keyboard_listener = keyboard.Listener(on_press=on_press)
keyboard_listener.start()
# 阻塞主线程
keyboard_listener.join()
mouse_listener.join()
标签:鼠标,python,listener,keyboard,print,mouse,监听
From: https://www.cnblogs.com/liwenchao1995/p/18010635