Using arrow keys with python can be tricky so the code below should help: –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
import curses # get the curses screen window screen = curses.initscr() # turn off input echoing curses.noecho() # respond to keys immediately (don't wait for enter) curses.cbreak() # map arrow keys to special values screen.keypad(True) try: while True: char = screen.getch() if char == ord('q'): break elif char == curses.KEY_RIGHT: # print doesn't work with curses, use addstr instead screen.addstr(0, 0, 'right') elif char == curses.KEY_LEFT: screen.addstr(0, 0, 'left ') elif char == curses.KEY_UP: screen.addstr(0, 0, 'up ') elif char == curses.KEY_DOWN: screen.addstr(0, 0, 'down ') finally: # shut down cleanly curses.nocbreak(); screen.keypad(0); curses.echo() curses.endwin() |