pythonpython-3.xterminaleffect

Making a terminal-slide-up effect in python


I'm working on a project where i need a transition effect when needed. I'm running this python project through 'cool-retro-term' a CRT terminal emulator.

I want to make it like the old-school CRT terminal's where the screen smoothly slides up all characters to present the next line or to refresh the screen. Like this: Terminal Slide Effect

NOT THE CHARACTERS BEING PRINTED INDIVIDUALLY, BUT THE SCROLLING OF THE SCREEN.

So far the best I've done is create a function with a bunch of empty prints in a loop:

import time

def slide_up():
    for _ in range(30):
        print("")
        time.sleep(0.03)
    clear()

The clear() is a function that clears the terminal screen:

clear = lambda: os.system('clear')

If anyone knows how I could accomplish this effect I'd greatly appreciate it.


Solution

  • To directly control the screen scrolling, you need something like VT100 control codes. Try this demo. It uses different VT100 control codes to hide/show the cursor and scroll up/down.

    import time
    
    def smooth_scroll(lines=10, delay=0.1):
        """
        Smoothly scrolls the terminal up or down a specified number of lines with a delay using VT100 escape codes.
    
        Args:
        lines (int): The number of lines to scroll. Positive values scroll up, negative values scroll down.
        delay (float): The delay in seconds between each line scroll.
        """
        print("\033[?25l", end="", flush=True)  # Hide the cursor
        
        if lines > 0:
            for _ in range(lines):
                print("\033[1S", end="", flush=True)  # Scroll up one line
                time.sleep(delay)
        else:
            for _ in range(abs(lines)):
                print("\033[1T", end="", flush=True)  # Scroll down one line
                time.sleep(delay)
                
        print("\033[?25h", end="", flush=True)  # Show the cursor
    
    # Example usage
    smooth_scroll(lines=20, delay=0.2)  # Scrolls up 20 lines
    smooth_scroll(lines=-10, delay=0.2)  # Scrolls down 10 lines
    

    You have to be using a terminal that supports VT100 control codes.