0

I want to make a program that runs a code when you just click on a button on a keyboard for example, I press A and some code runs, but I do not have to press enter or input it to run it. Just like in video games, your character moves if you press W. Sorry if it is worded badly, I am pretty confused about this.

Keep in mind please it's Python 2.7

lllll 22
  • 13
  • 2

1 Answers1

1

I am assuming you mean in the console and not in any gui like tkinter or something.

I'd suggest using pynput (pip install pynput)

with code similar to this

from pynput.keyboard import Key, Listener

def on_press(key):
    print('{0} pressed'.format(
        key))

def on_release(key):
    print('{0} release'.format(
        key))
    if key == Key.esc:
        # Stop listener
        return False

while True:
    with Listener(on_press=on_press,on_release=on_release) as listener:
        listener.join()

word of warning: The above code also catches exit keys so ctrl + c will not stop the console. for that you would need to implement something to break out of the While loop when ctrl+c is pressed.

Marc Frame
  • 923
  • 1
  • 13
  • 26