如何在 Pynput 的按下和释放功能之间设置一个计时器?

How to make a timer between on press and on release functions on Pynput?

我想制作一个定时器,当没有按键被按下时启动,当任意键被按下时,定时器被重置。我真的不知道如何做到这一点,但我认为使用线程和时间库是可能的。

示例代码:

import threading, time
from pynput import keyboard

keys = []

def write_keys(keys):
   for key in keys:
        k = str(key).replace("'", "")
        # do some stuff here

def on_press(key):
    # the timer will reset if a key is pressed
    global keys
    keys.append(key)
    write_keys(keys)
    keys = []

def on_release(key):
    print(f'{key} was released')
    # the timer will start when no key is pressed

# Collecting events
with keyboard.Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

这看起来很简单,下面的代码将打印自您上次按下任意键以来的秒数。

import time
from pynput import keyboard

counter_time = 0

def on_press(key):
    # the timer will reset if a key is pressed
    global counter_time
    counter_time = 0

# Collecting events
listener = keyboard.Listener(on_press=on_press)
listener.start()
while True:
    print(f"Now the time is:{counter_time} since the last time you pressed any keys")
    time.sleep(0.5)
    counter_time += 0.5

另一个可能的答案是使用线程和 ctypes 库。如果您想继续在函数 on_pressed.

上做事,我会推荐这个
import threading
from pynput import keyboard
from ctypes import Structure, windll, c_uint, sizeof, byref
from time import sleep
class LASTINPUTINFO(Structure):
    _fields_ = [
        ('cbSize', c_uint),
        ('dwTime', c_uint),
    ]

def get_idle_duration():
    while True:
        lastInputInfo = LASTINPUTINFO()
        lastInputInfo.cbSize = sizeof(lastInputInfo)
        windll.user32.GetLastInputInfo(byref(lastInputInfo))
        millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
        millis = millis / 1000.0
        print(millis)
        sleep(1) 
    #return  millis

keys = []

def write_keys(keys):
   for key in keys:
        k = str(key).replace("'", "")
        print(k)

def on_press(key):
    global keys
    keys.append(key)
    write_keys(keys)
    keys = []

listener = keyboard.Listener(on_press=on_press)
last_input_info = threading.Thread(target=get_idle_duration)
listener.start()
last_input_info.start()
listener.join()
last_input_info.join()