怎样让文本在print()和input()中一次显示一个?

2024-04-25 23:16:02 发布

您现在位置:Python中文网/ 问答频道 /正文

几乎像一个RPG游戏,我想让文本似乎有人在键入他们。我知道如何使用python中的print()函数,包括sleep()和系统标准冲洗?你知道吗

如何在输入函数之前输入文本?你知道吗

例如,我希望What is your name?被打印出来,然后用户将输入他的名字。你知道吗


Tags: 函数用户name文本游戏your标准键入
2条回答

您可以使用以下代码:

import time,sys

def getinput(question):
    text = input(question)
    for x in text:
        sys.stdout.write(x)
        sys.stdout.flush()
        time.sleep(0.00001) #Sets the speed of typing, depending on your system

现在每次调用getinput("Sample Question"),都会根据传递给函数的问题得到用户的输入。你知道吗

您可以使用:

text = 'What is your name? '
for x in text:
   sys.stdout.write(x)
   sys.stdout.flush()
   time.sleep(0.00001)
name = input()

您还可以随机化每个循环的睡眠时间,以便更好地模拟键入,如下所示:

import time,sys,random
text = 'What is your name? '
for x in text:
   sys.stdout.write(x)
   sys.stdout.flush()
   time.sleep(random.uniform(.000001, .000019))
name = input()

正如Tomerikoo指出的,有些系统有更快/较慢的延迟,因此您可能需要在另一个系统上使用统一的(.01,.5)。我使用OS/X

在windows上,这可能效果更好。感谢Tomerikoo:

import time,sys,random
text = 'What is your name? '
for x in text:
   print(x, end="", flush=True)
   time.sleep(random.uniform(.000001, .000019))
   # or smaller sleep time, really depends on your system:
   # time.sleep(random.uniform(.01, .5))
name = input()

相关问题 更多 >