python 监听鼠标和键盘
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()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!