如何在Python中几秒后删除打印语句本身?

问题描述 投票:0回答:2

我正在尝试制作一款基于文本的冒险游戏,我希望能够让文本自行删除。 例如,游戏将使用

print()
语句打印文本,然后在 5 秒后将其删除或对玩家隐藏。

我尝试查找其他人关于此问题的问题,但找不到任何信息。我不知道要使用什么命令或与之相关的任何内容,请帮忙。

python
2个回答
2
投票

您想在指定时间后清除整个终端吗?

import os  
os.system('cls' if os.name == 'nt' else 'clear')

查看原始来源这里

如果您只想清除一行:

print("your game text here", end = '\r')
  • 在显示文本时使用
    \r
    作为结束字符(应该在 5 秒后删除),
  • 然后打印空格 (
    print(" "*length)
    ),其中 length 是游戏文本的假定最大长度

查看原始来源这里

希望您觉得这很有用!


-1
投票
    import time
import sys

def print_and_replace(text, replacement_text, delay=5):
    print(text, end='', flush=True)  
    time.sleep(delay)  
    

    sys.stdout.write('\r' + ' ' * len(text)) 
    sys.stdout.write('\r')  
    sys.stdout.write(replacement_text)  
    sys.stdout.flush()

print_and_replace("This will be replaced in 5 seconds...", "This is the new text!", 5)
© www.soinside.com 2019 - 2024. All rights reserved.