如何创建一个计时器,计时在 python 中按下某个键的时间?

How to create a timer that times for how long a certain key is pressed in python?

keys_pressed=[]    
def keytracker():

 def on_press(key):
     global start,stop
     start=time.time()
     print(key)
     keys_pressed.append('t')
 def on_release(key):
     stop = time.time()
     print(stop-start)
     if key==Key.esc:
         return False
 with Listener(on_press=on_press,on_release=on_release) as listener:
     listener.join()

是否可以在按下某个键时启动计时器,然后在释放该键时打印该键被按下了多长时间而无需 time.sleep()?如果是这样,是否可以同时使用多个键执行此操作并打印每个键被按下的时间?例如:如果我按住“w”10 秒,然后还按住“d”5 秒(同时按住 w),我可以计算每个键被按下的时间,然后将时间计入列表或元组中以供使用后面的数字?

对于计时器,要记住的主要事情是,当按下一个键时,该键会重复,re-triggers 键按下事件。要存储每个键的开始时间,您可以使用字典。在按键事件中,检查字典中的键,如果键不在字典中,则设置键时间。在key up事件中,打印时间差并从字典中删除key。

这是更新后的代码:

from pynput.keyboard import Key, Listener
import time

keys_pressed={}  # dictionary of keys currently pressed

def on_press(key): # gets re-called a key repeats
     if key not in keys_pressed:  # if not repeat event
         keys_pressed[key] = time.time() # add key and start time
         
def on_release(key):
     print (key, time.time() - keys_pressed[key])  # time pressed
     del keys_pressed[key] # remove key from active list
     if key==Key.esc:
         return False
         
with Listener(on_press=on_press,on_release=on_release) as listener:
     listener.join()