【问题标题】:How would I print out a string one letter at a time using Python Curses?如何使用 Python Curses 一次打印一个字符串?
【发布时间】:2021-12-30 15:24:44
【问题描述】:

对于我的控制台应用程序中的某些样式,我经常使用这样的代码让字符串一次打印出一个字符:

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(),但没有区别。

【问题讨论】:

    标签: python python-curses


    【解决方案1】:

    将字符串写入屏幕后需要调用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)
    

    按您的预期工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多