GUI Text Box in Terminal

Having a GUI in the terminal would be ”interesting”. Here is some code to display a box with a title and content. Its far from a GUI, but its a start. This idea might just be used in my autonomous buoy project for displaying telemetry data.

from colorama import Fore, Back, Style

def gen_text_box(title, size_x, size_y, content):
    """
    Arguments:
    title - Title string of box displayed at the top
    size_x - Horizontal character size of the box
    size_y - Vertical character size of the box
    content - String of content that needs to be displayed in the box

    Returns:
    line - string with box embedded, ready to be printed
    """
    
    BLANK_ROWS = 1
    BLANK_COL = 2

    t_start = int(size_x/2 - len(title)/2)
    t_stop = t_start + len(title)
    line = "" # Initialise drawing string to nothing

    # Draw top line
    for i in range(size_x):
        if i == 0:
            line = line + "\u250C"	
        elif i == size_x - 1:
            line = line + "\u2510"
        else:
            line = line + "\u2500"

    # Insert title
    start = line[0:t_start]
    end = line[t_stop:]
    line = Fore.CYAN+start+Fore.WHITE+title+Fore.CYAN+end # Make title white

    # Seperate content into an array of rows
    content_list = content.split('\n')

    # Draw side lines as well as content
    line = line + "\n"
    for i in range(size_y):
        c_line = ""
        for j in range(size_x):
            if j == 0:
                c_line = c_line + "\u2502"
            elif j == size_x-1:
                c_line = c_line + "\u2502"
            else:
                c_line = c_line + " "
        c_line = c_line + "\n"

        # Insert content line
        if i < len(content_list) + BLANK_ROWS and i > BLANK_ROWS-1:
            start = c_line[0:BLANK_COL]
            end = c_line[len(content_list[i-BLANK_ROWS]) + BLANK_COL:]
            c_line = Fore.CYAN+start+Fore.WHITE+content_list[i-BLANK_ROWS]+Fore.CYAN+end # Make title white
        line = line + c_line

    # Draw bottom line
    for i in range(size_x):
        if i == 0:
            line = line + "\u2514"	
        elif i == size_x - 1:
            line = line + "\u2518"
        else:
            line = line + "\u2500"
    line = line + "\n"
    return  line

# Earnings
monthly_earnings = 30000
daily_earnings = monthly_earnings/30.5
hourly_earnings = daily_earnings/8

# Want to spend
spend = 2500

# Calculations
days_work = round(spend/daily_earnings,3)
hourly_work = round(spend/hourly_earnings,2)

content = "Spending " + str(spend) + " amounts to: \n" +\
           str(hourly_work) + " hours of work \n" +\
           str(days_work) + " hard days of labour"

print(gen_text_box("Spendy", 40, 4, content))

 

Posted in Things.

Leave a Reply

Your email address will not be published. Required fields are marked *