I have this sample code where I write on the screen if the enter key is pressed but when I run the code nothing happens and nothing is written on the screen.
I know I can use stdscr.getch()
, but for some reason I don't want to use them.
import curses
def main(stdscr):
stdscr.keypad(True)
while 1:
Key = stdscr.getkey()
if Key == curses.KEY_ENTER:
stdscr.addstr(0,0,'u pressed enter')
stdscr.refresh()
curses.wrapper(main)
On my computer with Linux I have to use
if Key == '\n':
or
if ord(Key) == 10:
It seems getkey()
doesn't treat ENTER
as special key and it doesn't return curses.KEY_ENTER
. OR maybe it depens on terminal - some of then may have option to define code for ENTER
and/or BACKSPACE
.
EDIT:
I found out that for special keys getkey()
gives me strings like "KEY_LEFT"
instead of integer value curses.KEY_LEFT
. But get_wch()
gives integer value curses.KEY_LEFT
(and char for normal keys) - but it still treats ENTER
as '\n'
You should simply use print()
to check what you get in variables.
print(Key, type(Key))
and when you see it is <class str>
print( ord(Key) )
You could also compare it with constant
print( Key, curses.KEY_ENTER, Key == curses.KEY_ENTER )
EDIT:
I tested it with this code on Linux Mint 20 MATE, Python 3.8, in Mate-Terminal.
import curses
def main(stdscr):
while True:
#key = stdscr.getch() # always integer (keycode), native/Polish char WRONG (two wrong integers)
#key = stdscr.getkey() # char or string (keyname), native/Polish char WRONG (two wrong chars)
key = stdscr.get_wch() # char or integer (keycode), native/Polish char OK
print('key:', type(key), key, end='\n\r')
if isinstance(key, str):
print('len:', len(key), end='\n\r')
if len(key) == 1:
print('ord:', ord(key), end='\n\r')
else:
print('keyname:', curses.keyname(key), end='\n\r')
print('---', end='\n\r')
stdscr.refresh()
# --- main ---
#print('curses.KEY_ENTER:', curses.KEY_ENTER)
#print('curses.KEY_BACKSPACE:', curses.KEY_BACKSPACE)
curses.wrapper(main)
For me the best is get_wch()
because it works correctly with native (Polish) chars.
getch() - always integer (keycode), native/Polish char WRONG (two wrong integers)
getkey() - char or string (keyname), native/Polish char WRONG (two wrong chars)
get_wch() - char or integer (keycode), native/Polish char OK
EDIT:
For key F1
it needs
string "KEY_F(1)"
for getkey()
getkey() == "KEY_F(1)"
integer 265
or curses.KEY_F1
for get_wch()
and getch()
get_wch() == 265
get_wch() == curses.KEY_F1
getch() == 265
getch() == curses.KEY_F1