简体   繁体   English

如何创建一个计时器来计时在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()

Is it possible to start a timer when a key is pressed, and then when the key is released, print how long that key was pressed for without time.sleep() ?是否可以在按下某个键时启动计时器,然后在释放该键时,打印该键按下了多长时间而不使用time.sleep() If so, is it possible to do this with multiple keys, simultaneously and print how long each key was pressed?如果是这样,是否可以使用多个键同时执行此操作并打印每个键被按下的时间? For example: If i hold "w" for 10 seconds, and then also hold "d" for 5 seconds (while holding w) can i time how long each key was pressed for, then put time counted in a list or tuple to use the number(s) later?例如:如果我按住 "w" 10 秒,然后还按住 "d" 5 秒钟(同时按住 w),我可以计算每个键被按下的时间,然后将时间放在列表或元组中以供使用之后的数字?

For the timer, the main thing to remember is that when a key is held down, the key repeats and re-triggers the key down event.对于定时器,要记住的主要事情是当一个键被按下时,该键会重复并重新触发键按下事件。 To store the start time for each key, you can use a dictionary.要存储每个键的开始时间,您可以使用字典。 In the key down event, check the dictionary for the key and set the key time if the key is not in the dictionary.在key down事件中,检查key的字典,如果key不在字典中,设置key的时间。 In the key up event, print the time difference and remove the key from the dictionary.在 key up 事件中,打印时差并从字典中删除 key。

Here is the updated code:这是更新后的代码:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM