0

I am trying to control a robot with the keyboard. I want to get the user input from the keyboard and call the respective function, it could be the letters "l" for left, "r" for right and "e" for exit.

direction = ""
while direction != "e":
    direction = input("enter direction: ")
    if direction == "r":
        goRight()
    elif direction == "l":
        goLeft()

The code is working but the user have to type the enter key each time. Is there a solution to read the key immediately when typed?

1
  • 1
    What about this? I think pygame offers something similar as well. Commented Sep 27, 2021 at 10:36

1 Answer 1

1

Try readchar. It's really simple but should fit your needs:

Simple example

import readchar 

while True:
    key = readchar.readkey()
    print(key)

Implemented in your function

direction = ""
while direction != "e":
    direction = readchar.readkey()
    if direction == "r":
        goRight()
    elif direction == "l":
        goLeft()
Sign up to request clarification or add additional context in comments.

3 Comments

Or if you don't want to use readchar you can try something from here: stackoverflow.com/questions/3523174/…
I get an error ModuleNotFoundError: No module named 'readchar', even after installing readchar with pip install readchar
Fixed the problem with python -m pip install readchar. It's working perfectly, thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.