0
\$\begingroup\$

I want the user to press on any letter of the alphabet; it should block the input from the rest of the keys. How can I do this using pygame?

Keys=pygame.key.get_pressed()
\$\endgroup\$
1
\$\begingroup\$

It's not exactly 'only allowing letters', but more 'only responding to letters'.

I'm not familiar with pygame, and my python is rusty, but according to the documentation, you could do something like this:

press=pygame.key.get_pressed()
  for i in xrange( pygame.K_a, pygame.K_z + 1 ): 
    if press[i] == True:
      name=pygame.key.name(i) 
      # do something with the key

However, I must emphasize the documentation of get_keypressed:

Getting the list of pushed buttons with this function is not the proper way to handle text entry from the user. You have no way to know the order of keys pressed, and rapidly pushed keys can be completely unnoticed between two calls to pygame.key.get_pressed(). There is also no way to translate these pushed keys into a fully translated character value. See the pygame.KEYDOWN events on the event queue for this functionality.

Depending on what you exactly intend to do with these alphabet letters, you might want to use the event route instead.

\$\endgroup\$
8
  • \$\begingroup\$ It works in the sense that it doesn't take an input from any other key except the alphabet, however, when I print the name of the key pressed, I recieve this outcome:<built-in function name> \$\endgroup\$
    – noob96
    Mar 21 '17 at 18:37
  • \$\begingroup\$ @AthR Are you sure you print the right thing? \$\endgroup\$
    – Vaillancourt
    Mar 21 '17 at 18:50
  • \$\begingroup\$ I printed the variable name \$\endgroup\$
    – noob96
    Mar 21 '17 at 18:51
  • \$\begingroup\$ I am soo sorry, I made a mistake. Instead of name=pygame.key.name(i), I wrote name=pygame.key.name. Thanks, it works now \$\endgroup\$
    – noob96
    Mar 21 '17 at 18:55
  • 1
    \$\begingroup\$ if x == True is less nice than just if x, similarly if x == False should be if not x \$\endgroup\$ Mar 21 '17 at 22:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .