使用 python 监听鼠标和键盘事件

Listen to mouse and keyboard events using python

如果键盘或鼠标有一段时间未使用,我会尝试提示错误消息。为此,我尝试了 pynput 模块,这对我来说不值得。谁能帮我解决这个问题,谢谢

如果您在五秒钟内不移动(或单击)鼠标并按下键盘,此代码将打印 (xxxxx)。

from pynput import mouse,keyboard
import time
def on_move(x, y):
    global LastTime
    LastTime = time.time()

def on_click(x, y, button, pressed):
    global LastTime
    LastTime = time.time()

def on_scroll(x, y, dx, dy):
    global LastTime
    LastTime = time.time()

def on_press(key):
    global LastTime
    LastTime = time.time()

LastTime = time.time()
listener = keyboard.Listener(on_press=on_press)
listener.start()
listener = mouse.Listener(on_move=on_move,on_click=on_click,on_scroll=on_scroll)
listener.start()
while True:
    if time.time()-LastTime >= 5: # the break time,5 is second
        print("You need break your computer")
        LastTime = time.time()