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 whenever the key is pressed and held down.
            Asked
            
        
        
            Active
            
        
            Viewed 974 times
        
    -5
            
            
        - 
                    show your code and what you found in Google. – furas Nov 30 '19 at 09:06
- 
                    Seems similar/identical to: https://stackoverflow.com/questions/24072790/detect-key-press-in-python More details on keyboard can be found here: https://pypi.org/project/keyboard/ – mtndoe Nov 30 '19 at 09:07
- 
                    when you press key then you can set variable `pressed = True`, when you release key then you can set `pressed = False` and between both methods you can check `pressed` to see if you still keep pressed key. – furas Nov 30 '19 at 09:08
- 
                    @furas I am new to python so can you explain how this would look built out? – Victor Mora Nov 30 '19 at 10:19
- 
                    what module do you use for key presse ? PyGame, pyglet, pynput, other ? – furas Nov 30 '19 at 11:11
- 
                    @furas I am thinking of using pynput. Lets say I want create a while loop that will continue to print a letter until I release it. – Victor Mora Nov 30 '19 at 11:56
1 Answers
0
            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)
    if event == KeyCode.from_char('a'):
        print("hold pressed: a")
with Listener(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 ---
def get_pressed(event):
    global key_a # inform function to use external/global variable instead of local one
    if event == KeyCode.from_char('a'):
        key_a = True
def get_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 listener
while True:
    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
 
    
    
        furas
        
- 134,197
- 12
- 106
- 148
