1

Is there an easier way to get keyboard input in Pygame than specifying each individual key? For instance,

if event.key == pygame.K_a:
    command = command + "a"
elif event.key == pygame.K_b:
    command = command + "b"
elif event.key == pygame.K_c:
    command = command + "c"

Is there some way to use a function to do this for me?

1 Answer 1

2

If an entirely different action is necessary for each key, then there isn't really a better way. If multiple keys result in similar actions, where say a single function f could take the key as an argument, you could use an in expression like so:

if event.key in (pygame.K_a, pygame.K_b, pygame.K_c):
    f(event.key)

An in expression evaluates to True if what's on the left side is contained within what's on the right side. So, with that code if the key pressed is 'a', 'b', or 'c,' the function f will be called with the key as an argument.

As a practical example, say you want either the 'Esc' or 'q' key to quit the program. You could accomplish that this way:

if event.key in (pygame.K_ESCAPE, pygame.K_q):
    pygame.quit()

The above code is effectively the same as:

if event.key == pygame.K_ESCAPE:
    pygame.quit()
elif event.key == pygame.K_q:
    pygame.quit()

Edit

From a comment, command is a string that is concatenated to. If say you wanted to add any key a-z that was pressed to command, you could do this:

if event.key in range(pygame.K_a, pygame.K_z + 1):
    command += event.unicode
Sign up to request clarification or add additional context in comments.

7 Comments

Thank you! Is there a way I could make f() print out the ascii value of the key? simply using print() prints out the decimal form.
I believe print(event.unicode) would do it, but it looks like that's only available on KEYDOWN events, as seen here (see the yellow box a little ways down the page), so make sure you're checking for those rather than KEYUP events.
I'm creating an application where the user types into a text box and presses enter. the text in the box is assigned to the variable command. I then call os.system(command). Sort of like the run-dialog in GNOME.
the code if event.key in (pygame.K_a, pygame.K_b, pygame.K_c): print(event.unicode) Works perfectly! Thank you!
You're welcome. I've added a little more information in an edit. Good luck!
|

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.