Python 诅咒 window.getch() returns 错误的值

Python Curses window.getch() returns wrong value

为什么当我 运行 这个代码 box.getch() returns 一个错误的值,当我把 box.getch() 改成 screen.getch() 它 returns正确的价值?我一直在互联网上查找,没有人说 getch() 只适用于屏幕。如果你按其中一个箭头,它 returns 27 这是 ESC 的字符。 (此代码应打印字符,直到用户按 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()

答案(参见Bug with refresh in python curses)是添加box.keypad(1)。有几行是不必要的 - 示例中已标记:

    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()
#!/usr/bin/python3
import          curses
screen        = curses.initscr(      )
screen.border ( 0                    )
e             = curses.noecho(       )
e             = curses.cbreak(       )
e             = curses.start_color(  )
e             = curses.init_pair(  1 , curses.COLOR_GREEN, curses.COLOR_CYAN)
e             = curses.curs_set(   0 )
highlightText = curses.color_pair( 1 )
normalText    = curses.A_NORMAL
box           = curses.newwin(  20, 60, 1, 1 )
box.keypad( 1 )
box.box(      )
box.refresh(  )
e =   x  =  1
try:
  while x != 50 :            #     27  ESC
    box.erase(       )
    cc="WTF?"
    try:     cc=str(chr(x))
    except:  cc="ERR"
    box.addstr( 8, 8, "key 2 to quit, you pressed" + str(x) + "  '" + cc + "'" )
    screen.border( 0 )
    box.border(    0 )
    x = box.getch(   )
except : print("oh my!")
finally: curses.endwin() # avoids messed up console!