Make a print vanishin Python

38 views Asked by At

How can i make a text appear and after 3 second disappear? I'm a beginner and trying to make a simple little game.

A basic code can easily help me out.

2

There are 2 answers

0
ProfDFrancis On

Use the "\r" to return to the start of the line

from time import sleep

print("Hello",end="\r")
sleep(3)  # Time in seconds
print("     ",end="\r")

0
SIGHUP On

Here's an example of some ANSI sequences that will help you:

from time import sleep
from sys import stdout

CSI = '\x1B['

def display_then_hide(msg, idle=3):
    try:
        stdout.write(f'{CSI}?25l') # hide cursor (because it looks nicer)
        stdout.write(msg) # output message
        stdout.flush() # flush
        sleep(idle) # wait a while
    except KeyboardInterrupt:
        pass
    finally:
        stdout.write(f'\r{CSI}K{CSI}?25h') # CR, clear to EOL then show cursor

display_then_hide('Hello world!')

Note:

try/finally is used to ensure that the cursor is shown even if, for example, the sleep is interrupted (e.g., Ctrl-C)