简体   繁体   中英

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

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. In the key up event, print the time difference and remove the key from the dictionary.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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