pythonpython-3.xnew-windowtui

Python hide already printed text


I'm creating a simple two-player board game where each player must place pieces on their own boards. What I would like to do is by either:

I have tried clearing the screen but haven't been able to completely remove all the text. I don't have a preference; whichever method is easier. Also, if it would be easier to use a different method that I haven't thought of, all other suggestions are welcome. Thanks in advance!

EDIT: Other solutions give the appearance that text has been cleared but a user could still scroll up and see the text that was cleared. I'd like a way to remove any way that a user could see this text.

EDIT 2: Please read the other answers and the comments as they provide a lot of information about the topic as a whole. In particular, thanks to @zondo.


Solution

  • I would recomend a simple ANSI escape code to move the cursor position, Cursor Escape Codes, to the start of the board everytime. There is also an ANSI escape code that completly clears the console though, so you can choose.

    If you are on windows you must first import colorama a module that makes windows prompt be able to use the ANSI codes as such:

    import colorama   # OR: from colorama import init
    colorama.init()   # AND THEN: init()
    

    So if your board has n rows, after the user input for their turn, you move the cursor UP n rows + however many were required for user input, so if you wrote Input row, col: ... then you would go UP n+1, etc...

    A simple example:

    numLines = 1
    print("Hello world!")
    print("\033[<{0}>A".format(numLines), "This came AFTER hello world line")