我在ncurses(linux(中遇到了编码问题。我试图在Python中复制ncurses在C中编程HOWTO的示例7。我确实设法使这个例子运行起来了。
import curses
@curses.wrapper
def main(main_screen):
w, h = 5, 3
x, y = curses.COLS // 2, curses.LINES // 2
def mkwin(w, h, x, y):
win = curses.newwin(h, w, y, x)
win.box(0, 0)
win.refresh()
return win
def clearwin(win):
win.border(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ')
win.refresh()
main_screen.addstr("Press Q to quit.")
main_screen.refresh()
testwin = mkwin(w, h, x, y)
while True:
key = main_screen.getch()
if key in {curses.KEY_BACKSPACE, ord('q')}:
break
if key == curses.KEY_LEFT:
clearwin(testwin)
del testwin
x -= 1
testwin = mkwin(w, h, x, y)
if key == curses.KEY_RIGHT:
clearwin(testwin)
del testwin
x += 1
testwin = mkwin(w, h, x, y)
if key == curses.KEY_UP:
clearwin(testwin)
del testwin
y -= 1
testwin = mkwin(w, h, x, y)
if key == curses.KEY_DOWN:
clearwin(testwin)
del testwin
y += 1
testwin = mkwin(w, h, x, y)
但是,我想删除第一个有"Press Q to quit."
消息的屏幕。所以我换了
main_screen.addstr("Press Q to quit.")
main_screen.refresh()
testwin = mkwin(w, h, x, y)
至
testwin = mkwin(w, h, x, y)
但相反,我有一个空的第一个屏幕,它会一直呆到我按下一个键。显然,main_screen
的getch()
功能会导致整个屏幕清空,所以我不得不使用testwin
的getch()
。
然而,testwin.getch()
方法并没有为一次按键返回一个漂亮的整数代码:它返回的是调整键代码。例如,对于Key Up,它返回27
,然后返回91
,而不是返回单个259
main_screen.getch()
。如何配置testwin
,使getch
返回testwin
的值,如同返回main_screen
的值一样?
注意:我尝试使用main_screen.subwin
而不是curses.newwin
,但它没有改变任何内容。
python诅咒"包装器";调用keypad
方法,该方法不是newwin
的默认方法。源代码是这样做的:
# In keypad mode, escape sequences for special keys
# (like the cursor keys) will be interpreted and
# a special value like curses.KEY_LEFT will be returned
stdscr.keypad(1)
如果添加win.keypad(1)
,它将解决该问题。