如何使用Python Curses一次打印一个字符串一个字母



对于控制台应用程序中的某些样式,我通常会使用以下代码一次打印出一个字符:

import time

def run():
    the_string = "Hello world!"
    for char in the_string:
        print(char, end='', flush=True)
        time.sleep(0.1)
    input()

run()

我希望对Python Curses也能做到这一点,这样我就可以在应用程序的其他方面有更多的灵活性。这就是我目前所拥有的:

import curses
import time

def run(stdscr):
    stdscr.clear()
    the_string = "Hello world!"
    for char in the_string:
        stdscr.addstr(char)
        time.sleep(0.1)
    stdscr.getch()

curses.wrapper(run)

问题是,在将文本放入控制台之前,只需等待for循环的持续时间。区别是flush=True,所以我尝试在函数中的几个不同位置包含curses.flushinp(),但没有区别。

将字符串写入屏幕后,需要调用stdscr.refresh()来刷新屏幕。

import curses
import time

def run(stdscr):
    stdscr.clear()
    the_string = "Hello world!"
    for char in the_string:
        stdscr.addstr(char)
        stdscr.refresh()
        time.sleep(0.1)
    stdscr.getch()

curses.wrapper(run)

如您所愿,效果良好。

相关内容