Search code examples
pythoninputterminalkeycurses

Translating a integer to a key


I have a very basic terminal UI in curses that looks like this:

│Option:                       Status:   Key: 
│description of option 1       [ON]       <267>
│description of option 2       [OFF]      <102>

The key is the key you have to press for the status to change. In the curses module (or in general) how can I tansform a key integer to a name?

If my key is ord('f') which is 102 I can chr(102) to get 'f' printed on the screen. But if my key is curses.KEY_F3 which is 267 I get funny symbols for chr(267). How can I print 'F3' from just the integer 267?

This is the copied output with chr() but in the console there is a box with a ? behind the Ä

│Option:                       Status:   Key:
│description of option 1       [ON]       <Ä>
│description of option 2       [OFF]      <f>

Solution

  • It looks like you need curses.keyname.

    curses.keyname(k) Return the name of the key numbered k. The name of a key generating printable ASCII character is the key’s character. The name of a control-key combination is a two-character string consisting of a caret followed by the corresponding printable ASCII character. The name of an alt-key combination (128–255) is a string consisting of the prefix ‘M-‘ followed by the name of the corresponding ASCII character.