1

I am writing a program to get keyboard inputs. Here is the code:

key = 0
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
    if event.type == pygame.KEYDOWN:
        for key in keys:
            if event.key == key:
                key = key
                if key != None:
                    print(key)
                    print(chr(key))
                    return chr(key)
                else:
                    return

The problem is that the key is too large in ASCII for chr() to handle. For example, when I press Caps Lock, it spits me an error. What I am trying to do is get the integer of the pygame.keydown and convert it to an ASCII character, then return that character. Is there any way, besides chr(), that won't give me the error?

ValueError: chr() arg not in range(0x110000)
accdias
  • 5,160
  • 3
  • 19
  • 31
  • 1
    Not every key is going to correspond to a character - what do you think `caps lock` should return? Better to just work with the integer values. – Mark Ransom Dec 25 '22 at 05:26
  • 1
    `key = key` doesn't make any sense in that context. Also, the `for` loop seems unnecessary when you can simply use `if key in keys`. – accdias Dec 25 '22 at 05:27
  • 2
    If the key event does represent a printable character, that character will already be in `event.unicode` - no conversion required. – jasonharper Dec 25 '22 at 05:30

1 Answers1

1

A user friendly name of a key can be get by pygame.key.name():

for event in pygame.event.get():
    if event.type == pygame.KEYDOWN:

        print(pygame.key.name(event.key))
Rabbid76
  • 202,892
  • 27
  • 131
  • 174