Search code examples
pythonkeyboardpygamespecial-characters

Get special characters from the key events


When a PyGame key event is fired, the letter associated with the key is gathered using chr(event.key). This doesn’t work when a key with a special character is pressed, such as æ, ø or å, on a Norwegian keyboard.

if event.type == pygame.KEYDOWN:
    characterNumber = event.key
    character = chr(characterNumber)
    print(character)

How can these characters be retrieved?


Solution

  • Instead of doing this:

    characterNumber = event.key
    character = chr(characterNumber)
    

    Try this:

    character = event.unicode
    

    According to the docs, a KEYDOWN event should have a unicode property which represents the unicode value of the key that was pressed, based on the current keyboard layout.

    http://www.pygame.org/docs/ref/event.html