简体   繁体   English

如何使用 Python 诅咒一次打印一个字符串?

[英]How would I print out a string one letter at a time using Python Curses?

For some style in my console applications, I'll often have a string print out one character at at time using code like this:对于我的控制台应用程序中的某些样式,我通常会使用如下代码一次打印一个字符串:

import time


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


run()

I am looking to do the same with Python Curses, so I can have some more flexibility in other aspects of the application.我希望对 Python 诅咒做同样的事情,这样我可以在应用程序的其他方面有更多的灵活性。 This is what I have so far:这是我到目前为止所拥有的:

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)

problem is this just waits for the duration of the for loop before putting the text on the console.问题是这只是在将文本放在控制台之前等待 for 循环的持续时间。 The difference is flush=True so I've tried to include curses.flushinp() at a few different places in the function, but it makes no difference.不同之处在于flush=True ,所以我尝试在function 的几个不同位置包含curses.flushinp() ,但这没有区别。

You need to call the stdscr.refresh() after writing the string to the screen to refresh the screen.您需要在将字符串写入屏幕后调用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)

works fine as you intended.工作正常,如你所愿。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM