0

I am trying to write a simple command line program in Windows, but it doesn't look very nice. Is there a library to generate CLIs that look closer to something like GUIs?

For example:

                         Hello Program 1.0 (bar with white background)

Progress Bar: (bar with green background like in Windows OS)

Some Labels...




Cancel (Button with blue background)                      OK (Button with blue background)

I wasn't able to find a solution on the internet, yet. I don't want to make a real graphic window, I want to use the command line.

12
  • Rather than voting to close this, I suggest you edit your original post (OP), and say what you have tried, post a small amount of real code, and also show you researched this. Have a look at this SO post, but it doesn't look like good news: stackoverflow.com/questions/14779486/… Commented Sep 30, 2015 at 15:28
  • 2
    Who is closing the question? Who is downvoting, including legitimate answers? Is it so wrong to not know about curses and ask on SO? Commented Sep 30, 2015 at 15:29
  • I didn't find anything on the internet. That's my problem. Commented Sep 30, 2015 at 15:30
  • Yeah. I don't know about curses and want a community to help me. Commented Sep 30, 2015 at 15:31
  • @FilipDupanović I voted (among others) to close this question. It is too broad, asking for off-site resources, shows no effort from the OP, and is vague in what they want to do. It is as bad as questions get on this website. Commented Sep 30, 2015 at 15:31

3 Answers 3

3

You can use curses to place text anywhere: https://docs.python.org/2/howto/curses.html

For a Windows variant, you can use unicurses

Keep in mind this only lets you position the cursor on your window, it does not provide higher level modules to create buttons or widgets.

Sign up to request clarification or add additional context in comments.

4 Comments

I can't use it on windows. I am using Windows.
You can also read about tkinter. I think that some of the controls that you want can't be used in a console (like a button)
@aaossa: The OP specifically says that a CLI-only solution is required. Yes, it's clunkier than a proper GUI, but it is do-able.
2

You cannot achieve the goal of placing graphical elements on the command line. Whether or not you are programming for Windows or Linux, command line (CLI) applications can only make use of very broad elements, like escape sequences that create bold, blink, and so on and crude areas on the screen where data can be entered.

You can map control keys provided you have the right CLI library or toolkit, and you can prompt your users for something like

"Do you want to run this program again (y/n) ?"

and then if the answer is 'n', the program exits.

I would search the links given to you in various comments on your OP and one of the answers to see how to program in curses.

1 Comment

Thank you octopusgrabbus
1

Finally i found an own solution. (No buttons sadly :( )

Take a look at this code based on termcolor module and colorama (colorama must be installed via pip)

import os
import sys
import time
try:
    import colorama
except ImportError:
    raise ImportError("Please install the colorama package.\nYou can do pip install colorama on the command line.")
colorama.init()




# Modules
def cls():
    """ Clears the Screen """
    os.system("cls")

def printpos(text,posy):
    """ Goes to the line [posy] and writes the text there """
    sys.stdout.write("\033["+str(posy)+";1H")
    sys.stdout.write(text)
    sys.stdout.flush()

def title(text):
    """ Sets the title """
    #cls()
    sys.stdout.write("\033[1;1H")
    long = 80
    left = int(int(long - int(len(text))) / 2)
    right = int(int(long - int(len(text))) / 2)
    left = left * " "
    right = right * " "
    sys.stdout.write(cl(left+text+right,"grey","on_white"))
    if str(float(float(len(left+text+right)) / float(2.0)))[-1] == "0":
        None
    else:
        sys.stdout.write(cl(" ","grey","on_white"))
    sys.stdout.flush()


def entry(_title="TITLE",question="QUESTION",clear=True):
    """ Creates an input window. title=window title  question=prompt clear=[True|False] Clear Window before asking(recommended)"""
    if clear:
        cls()
    title(_title)
    lns = len(question.split("\n"))
    middle = 12
    long = 80
    posy = middle - lns
    if lns > 1:
        temp = question.split("\n")[0]
    else:
        temp = question
    posx = int(int(int(long)-int(len(temp))) / 2)
    sys.stdout.write(posy*"\n"+str(posx*" ")+question)
    sys.stdout.flush()
    sys.stdout.write(cl("\n"+str(long*" "),"grey","on_yellow"))
    sys.stdout.write(cl(" ","grey","on_yellow")+str(int(long-2)*" ")+cl(" ","grey","on_yellow"))
    sys.stdout.write(cl(str(long*" "),"grey","on_yellow"))
    sys.stdout.write("\033["+str(posy+lns+3)+";2H")
    sys.stdout.flush()
    ret = raw_input("-> ")
    cls()
    return ret
def waitenter(msg="Please Press Enter ->"):
    """ Entry function like press enter message """
    height = 25
    long = 80
    long = long - 1
    sys.stdout.write("\033["+str(height)+";1H")
    sys.stdout.write(cl(str(long*" "),"grey","on_red"))
    r()
    sys.stdout.write(cl(str(msg),"grey","on_red"))
    raw_input()

ATTRIBUTES = dict(
        list(zip([
            'bold',
            'dark',
            '',
            'underline',
            'blink',
            '',
            'reverse',
            'concealed'
            ],
            list(range(1, 9))
            ))
        )
del ATTRIBUTES['']


HIGHLIGHTS = dict(
        list(zip([
            'on_grey',
            'on_red',
            'on_green',
            'on_yellow',
            'on_blue',
            'on_magenta',
            'on_cyan',
            'on_white'
            ],
            list(range(40, 48))
            ))
        )


COLORS = dict(
        list(zip([
            'grey',
            'red',
            'green',
            'yellow',
            'blue',
            'magenta',
            'cyan',
            'white',
            ],
            list(range(30, 38))
            ))
        )


RESET = '\033[0m'


def colored(text, color=None, on_color=None, attrs=None):
    """Colorize text.

    Available text colors:
        red, green, yellow, blue, magenta, cyan, white.

    Available text highlights:
        on_red, on_green, on_yellow, on_blue, on_magenta, on_cyan, on_white.

    Available attributes:
        bold, dark, underline, blink, reverse, concealed.

    Example:
        colored('Hello, World!', 'red', 'on_grey', ['blue', 'blink'])
        colored('Hello, World!', 'green')
    """
    if os.getenv('ANSI_COLORS_DISABLED') is None:
        fmt_str = '\033[%dm%s'
        if color is not None:
            text = fmt_str % (COLORS[color], text)

        if on_color is not None:
            text = fmt_str % (HIGHLIGHTS[on_color], text)

        if attrs is not None:
            for attr in attrs:
                text = fmt_str % (ATTRIBUTES[attr], text)

        text += RESET
    return text

def r():
    sys.stdout.write("\r")
    sys.stdout.flush()

returnpos = r
raw_input = input

def cprint(text, color=None, on_color=None, attrs=None, **kwargs):
    """Print colorize text.

    It accepts arguments of print function.
    """

    print((colored(text, color, on_color, attrs)), **kwargs)


cprint("hallo","red","on_white")
cl = colored

if __name__ == "__main__":
    cls()
    title("Hello")
    cprint("That is an example window dialog.\nPython is cool\nWe like it\nIt is so cool.\nIt is awesome.","yellow")
    waitenter()
    cls()
    title("Now Welcome!")
    cprint("In 10 Seconds you are going to see a dialog...","green",end="\r")
    cntr = 10
    for i in range(10):
        r()
        cntr = cntr - 1
        time.sleep(1)
        print(colored("In "+str(cntr)+" Seconds you are going to see a dialog...","green",None,None),end="\r")
    you = entry("Your favourite?","What is your favourite number?")
    cls()
    title("Your favourite number is...")
    cprint(str(you),"magenta")

    waitenter("Please Press Enter to exit -> ")

You can try it. Thanks to Filip Dupanovic who supported me with my question.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.