Skip to content Skip to sidebar Skip to footer

Python Code That Returns True While Key Is Pressed Down False If Release?

I need a code in python that returns an if statement to be true if a key is pressed and held down and false if it is released. I would like this code to be able to be executed when

Solution 1:

On some systems keyboard can repeate sending key event when it is pressed so with pynput you would need only this (for key 'a')

from pynput.keyboard import Listener, KeyCode

def get_pressed(event):
    #print('pressed:', event)
    ifevent == KeyCode.from_char('a'):
        print("hold pressed: a")

withListener(on_press=get_pressed) as listener:
    listener.join()

But sometimes repeating doesn't work or it need long time to repeate key and they you can use global variable for key to keep True/False

from pynput.keyboard import Listener, KeyCode
import time

# --- functions ---defget_pressed(event):
    global key_a # inform function to use external/global variable instead of local oneif event == KeyCode.from_char('a'):
        key_a = Truedefget_released(event):
    global key_a

    if event == KeyCode.from_char('a'):
        key_a = False# --- main --

key_a = False# default value at start 

listener = Listener(on_press=get_pressed, on_release=get_released)
listener.start() # start thread with listenerwhileTrue:

    if key_a:
        print('hold pressed: a')

    time.sleep(.1)  # slow down loop to use less CPU

listener.stop() # stop thread with listener
listener.join() # wait till thread ends work

Post a Comment for "Python Code That Returns True While Key Is Pressed Down False If Release?"