3

I am trying to get keyboard input using Pygame using this command:

if event.type == pg.KEYDOWN:
    # ADD KEYBOARD EVENTS
    keys = pg.key.get_pressed()

I want to check if the button pressed represents a number, I already know how to check if a string represent a number using try/except command, but, in my code keys is not a string, it is a huge tuple - and I don't know how to get it in an efficient way because every time I look in the internet on how to get keyboard input, they need to equate keys to something like pygame.pygame.K_LEFT and I don't want to do this for each number and furthermore every number in the number-pad (right side).

Is there an efficient way to determine if a user clicked on a number? Thanks!

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
CodeCop
  • 1
  • 2
  • 15
  • 37

2 Answers2

4

pygame.key.get_pressed() returns a list with the state of all keyboard buttons. This is not intended to get the key of a keyboard event. The key that was pressed can be obtained from the key attribute of the pygame.event.Event object:

if event.type == pg.KEYDOWN:
    if event.key == pg.K_a:
        # [...] 

unicode contains a single character string that is the fully translated character:

if event.type == pg.KEYDOWN:
    if event.unicode == 'a':
        # [...] 

See also pygame.key.

Rabbid76
  • 202,892
  • 27
  • 131
  • 174
  • Hi thanks for the answer! It does work! Is there a way to check if a backspace is pressed using `event.unicode` ? – CodeCop Sep 29 '20 at 17:13
  • @StackOMeow a backspace can be recognized by `event.key == pg.K_BACKSPACE` or `pg.key.name(event.key) == "backspace"` – Rabbid76 Sep 29 '20 at 17:16
  • I am trying `if event.type == pg.K_BACKSPACE and len(current_id) > 0:` below the `if event.type == pg.KEYDOWN:` and it still does not work, assume current_id 's length is indeed bigger than 0 (I checked it) is it true how I wrote it? Thanks – CodeCop Sep 29 '20 at 17:20
  • 1
    @StackOMeow `event.type` -> `event.key` – Rabbid76 Sep 29 '20 at 17:21
0

The following code offers quite a neat solution, it ignores all inputs that aren't numbers without even using try/except:

if event.type == pg.KEYDOWN and event.unicode.isdigit():
    print(int(event.unicode))

I wasn't able to find a way to do this that was more compact on the web, so worked out this solution by researching how to check if a string is an integer.

How can I check if a string represents an int, without using try/except?