首页 > 解决方案 > 如何将 stdout.flush 函数应用于输入提示?

问题描述

我是编码新手,开始使用 Python 并想创建一个简单的基于文本的游戏,但我在第一个障碍中绊倒了。我想出了如何将“打字机”风格的进程合并到我的文本中,但仅限于写入屏幕的文本。

for char in "Welcome to my first game!\n": 
    print(char, end='') 
    sys.stdout.flush() 
    time.sleep(0.1)

如果我想对input函数的提示执行相同的操作,例如:

input("What is your name? \n")

我该怎么办?

还有一种方法可以将其应用于整个程序,而不是每次我想打印一行?

标签: python

解决方案


您可以将其用作启动器。我只是在使用你自己的代码。

def input_flush(): 
    for char in "Welcome to my first game!\nWhat is your name?\n":   
        print(char, end='', flush=True) 
        time.sleep(0.1)
    return input()

name = input_flush()

print("great to see you {}".format(name))

推荐阅读