Search code examples
pythonpython-2.7python-3.xcursespython-curses

Python Curses window.getch() returns wrong value


Why when I run this code the box.getch() returns a wrong value and when I change box.getch() into screen.getch() it returns the right value? I've been looking on internet and there is no one saying that getch() works only with screens. If you press one of the arrows it returns 27 which is the chr of ESC. (This code should print the character untill the user presses ESC...)

import curses
screen = curses.initscr()
curses.noecho()
curses.cbreak()
curses.start_color()
screen.keypad( 1 )
curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_CYAN)
highlightText = curses.color_pair( 1 )
normalText = curses.A_NORMAL
screen.border( 0 )
curses.curs_set( 0 )
box = curses.newwin( 22, 64, 1, 1 )
box.box()
box.addstr( 14, 3, "YOU HAVE PRESSED: ")

screen.refresh()
box.refresh()

x = box.getch()
while x != 27:
    box.erase()
    box.addstr( 14, 3, "YOU HAVE PRESSED: " + str(x) )
    screen.border( 0 )
    box.border( 0 )
    screen.refresh()
    box.refresh()
    x = box.getch()

curses.endwin()
exit()

Solution

  • The answer (see Bug with refresh in python curses) is to add box.keypad(1). There are a few lines which are unnecessary - those are marked in the example:

        import curses
        screen = curses.initscr()
        curses.noecho()
        curses.cbreak()
        curses.start_color()
        screen.keypad( 1 )    # delete this line
        curses.init_pair(1,curses.COLOR_BLACK, curses.COLOR_CYAN)
        highlightText = curses.color_pair( 1 )
        normalText = curses.A_NORMAL
        screen.border( 0 )
        curses.curs_set( 0 )
        box = curses.newwin( 22, 64, 1, 1 )
        box.keypad( 1 )
        box.box()
        box.addstr( 14, 3, "YOU HAVE PRESSED: ")
    
        screen.refresh()    # delete this line
        box.refresh()
    
        x = box.getch()
        while x != 27:
            box.erase()
            box.addstr( 14, 3, "YOU HAVE PRESSED: " + str(x) )
            screen.border( 0 )
            box.border( 0 )
            screen.refresh()  # delete this line
            box.refresh()     # delete this line
            x = box.getch()
    
        curses.endwin()
        exit()