Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Detecting is key press long or short in Python

while True:
    listener()

I want to make a loop that detects is the key press long or short. How can I do it?

I’ve tried to make a function (keyboard module) that checks is the key still pressed after 1 second, but it didn’t work.

def listener(key='p'):
    index = 0
    if keyboard.is_pressed(key):
        #Short press?
        index += 1
        print('Hm is it short?')
        if index == 1:
            print("It isn't!") #long press!
        else:
            print("It is!") #short press!
    time.sleep(1)

Here is the result:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Hm is it short? It isn’t! Hm is it short? It isn’t!

>Solution :

You can track when the key was pressed and when it was released. Then you can calculate the time passed between these two events and if it is greater than your specified time, you can interpret it as a long press:

import keyboard
import time

start = None
LONG_DURATION = 1  # second(s)

while True:
    event = keyboard.read_event()
    if event.event_type == keyboard.KEY_DOWN and event.name == "p" and start is None:
        # Key was pressed for the first time, capture start time
        start = time.time()
    elif event.event_type == keyboard.KEY_UP and event.name == "p":
        # Key is released
        duration = time.time() - start
        if duration > LONG_DURATION:
            print("Long press")
        else:
            print("Short press")
        # Reset start time to capture next press event as new start
        start = None

The reason why we need to check, if we already had a KEY_DOWN event is, that continuously pressing a key might trigger multiple KEY_DOWN events, so we use the check for start is None to measure the time between the first KEY_DOWN event and the KEY_UP event (and not the last KEY_DOWN event).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading