Search code examples
pythontoggle

Python: How to toggle a boolean in a while loop after pressing a key without it double activating?


I have an infinite while loop running until I hit a key to exit it. Currently, I have an if statement that toggles a boolean if I press a key.

if keyboard.is_pressed('s'):
    armed = not armed

When I run the loop and press the key, sometimes it activates twice because the key was down long enough during the press to be activated in the next iteration of the while loop.

Are there any solutions that don't involve putting a delay in the while loop? It is a cv2 based script so any delays will result in an fps drop of the video being captured.


Solution

  • You could keep track of the time you detect the press. Anything within a time interval from there is ignored.

    import time 
    
    last_press = time.time()
    key_delay_seconds = 1.0
    armed = False
    
    while True:
        if keyboard.is_pressed('s'):
            if cur_time := time.time() > last_press + key_delay_seconds:
                armed = not armed
                last_press = cur_time
                print(armed)