0

我想在终端中动态打印文本,curses但是当按下这种键时,以下代码不显示键向上/向下文本,而循环文本被更新。我做错了什么?我在 Mac OS Maverick 上。

import curses
import time

screen = curses.initscr()

curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)
i = 0

while True:
    i += 1

    event = screen.getch()
    screen.clear()

    if event == ord("q"):
        break

    elif event == curses.KEY_UP:
        screen.addstr("The User Pressed UP", curses.A_REVERSE)
        time.sleep(3)

    elif event == curses.KEY_DOWN:
        screen.addstr("The User Pressed DOWN", curses.A_BLINK)
        time.sleep(3)

    else:
        screen.addstr("Loop {0}".format(i))

curses.endwin()

我已经测试了上面的第二个代码,它运行良好。对我来说很奇怪...

import curses

screen = curses.initscr()

curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)
i = 0

while True:
    i += 1

    event = screen.getch()

    if event == ord("q"):
        break

    elif event == curses.KEY_UP:
        screen.clear()
        screen.addstr(
            "The User Pressed UP in the loop {0}".format(i),
            curses.A_REVERSE
        )

    elif event == curses.KEY_DOWN:
        screen.clear()
        screen.addstr(
            "The User Pressed DOWN in the loop {0}".format(i),
            curses.A_BLINK
        )

curses.endwin()
4

1 回答 1

0

解决方案是使用screen.refresh().

import curses
import time

screen = curses.initscr()

curses.noecho()
curses.curs_set(0)
screen.keypad(1)
screen.nodelay(1)

i = 0

while True:
    i += 1

    event = screen.getch()
    screen.clear()

    if event == ord("q"):
        break

    elif event == curses.KEY_UP:
        screen.addstr("The User Pressed UP", curses.A_REVERSE)
        screen.refresh()
        time.sleep(2)

    elif event == curses.KEY_DOWN:
        screen.addstr("The User Pressed DOWN", curses.A_BLINK)
        screen.refresh()
        time.sleep(2)

    else:
        screen.addstr("Loop {0}".format(i))

curses.endwin()
于 2014-03-06T22:17:29.247 回答