How to delete the print statement itself after a few seconds in Python?

I am trying to make a text-based adventure game and I want to be able to have text self-delete itself.
For example, the game will use the print() statement to print the text, which will then be deleted or hidden from the player after 5 seconds.

I’ve tried to find other people’s questions about this problem and can’t find any info. I don’t know what commands to use or anything related to that, please help.

New contributor

ShuckleZeke is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

3

Do you want to clear the whole terminal after the specified time?

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

See original source here

If you want to clear just one line:

print("your game text here", end = 'r')
  • use the r as the end character while displaying the text (which is supposed to be deleted after 5 seconds),
  • then print blank spaces (print(" "*length)) where length is the supposed max length of your game text

See original source here

Hope you find this useful!

2

Let’s do this by changing the Cursor position in the Windows console
befor you startd read about ctypes if you are not familiar with that

each character in console have position of X & Y so lets make class named COORD for this like way documents says

import ctypes

class COORD(ctypes.Structure):
    _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)]

    def __init__(self, x, y):
        self.X = x
        self.Y = y

now lets make class named TextField for your text with behavior you want
(show & hide)

import ctypes
from time import sleep



class TextField():
    STD_OUTPUT_HANDLE = -11
    hOut = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    text = ""
    def __init__(self,x,y,maxlegnth):
        self.pos = COORD(x,y)
        self.maxlegnth = maxlegnth
    
    def setText(self,text):
        if len(text) > self.maxlegnth:
            raise OverflowError(f"yout text legnth is {len(text)} but max legnth for this text field is {self.maxlegnth}")
        self.text = text
        

    def show(self,timelive=None):
        # if timelive not be set text never will be deleted
        ctypes.windll.kernel32.SetConsoleCursorPosition(self.hOut, self.pos)
        print(self.text)
        if timelive:
            sleep(timelive)
            del self
    
    
      
    def clearText(self):
        ctypes.windll.kernel32.SetConsoleCursorPosition(self.hOut, self.pos)
        print(" "*self.maxlegnth)
        
    def __del__(self):
        self.clearText()
        
    

so when you use del on obejct in python the __del__ method will be called

I could hide text like this

def show(self,timelive=None):
            ctypes.windll.kernel32.SetConsoleCursorPosition(self.hOut, self.pos)
            print(self.text)
            if timelive:
                sleep(timelive)
                self.clearText()

and this is work fine but i did use del and __del__ on purpose to be more flexible if you need to use it somewhere outside the class and make you familiar with that

so this the code will be something like this

import ctypes
from os import system
from time import sleep


class COORD(ctypes.Structure):
    _fields_ = [("X", ctypes.c_short), ("Y", ctypes.c_short)]

    def __init__(self, x, y):
        self.X = x
        self.Y = y

class TextField():
    STD_OUTPUT_HANDLE = -11
    hOut = ctypes.windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
    text = ""
    def __init__(self,x,y,maxlegnth):
        self.pos = COORD(x,y)
        self.maxlegnth = maxlegnth
    
    def setText(self,text):
        if len(text) > self.maxlegnth:
            raise OverflowError(f"yout text legnth is {len(text)} but max legnth for this text field is {self.maxlegnth}")
        self.text = text
        

    def show(self,timelive=None):
        ctypes.windll.kernel32.SetConsoleCursorPosition(self.hOut, self.pos)
        print(self.text)
        if timelive:
            # sleep takes a float number if you need half second use 0.5 etc.
            sleep(timelive)
            del self
    
    
      
    def clearText(self):
        ctypes.windll.kernel32.SetConsoleCursorPosition(self.hOut, self.pos)
        print(" "*self.maxlegnth)
        
    def __del__(self):
        self.clearText()
        
    

def main():
    # use this to celar screen
    system("cls")
    # text position x,y zero is top left corner
    textfield = TextField(x=0,y=0,maxlegnth=10)
    textfield.setText("test1")
    # creating a time delay of 2 seconds
    textfield.show(2)
    textfield.setText("test2")
    textfield.show(2)


main()

this is just dummy example. It might give you the right insight
in solving the problem

the Cursor Position start at top left corner so its x=0 and y=0
But in some operating systems it is different, which is rare

ctypes.WinDLL

    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)

New contributor

Omar is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật