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.

Filip Dupanović
  • 32,650
  • 13
  • 84
  • 114
Faminator
  • 888
  • 1
  • 10
  • 16
  • 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: http://stackoverflow.com/questions/14779486/curses-alternative-for-windows – octopusgrabbus Sep 30 '15 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? – Filip Dupanović Sep 30 '15 at 15:29
  • I didn't find anything on the internet. That's my problem. – Faminator Sep 30 '15 at 15:30
  • Yeah. I don't know about curses and want a community to help me. – Faminator Sep 30 '15 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. – Cory Kramer Sep 30 '15 at 15:31
  • I believe it's OK to close, but I also believe we have to educate new posters about the SO etiquette. – octopusgrabbus Sep 30 '15 at 15:32
  • I don't want a GUI Toolkit. I want a command line solution. But yeah if you guys think you i am stupid than close this question – Faminator Sep 30 '15 at 15:32
  • @Faminator We are not calling anyone stupid. We are saying you posted a bad question for this website. Your entire question is "I want ___ and I want ___ and I want ___ and I want ___". – Cory Kramer Sep 30 '15 at 15:34
  • Have a look here: http://stackoverflow.com/questions/11743257/how-to-format-an-output-in-python However, the advice you are getting is correct. You're not going to get buttons on the command line. There is no way anyone can help you with that. You can prompt your user to see if they want to cancel, but to have a button is not possible. I've been doing Linux "forms" programming for over a decade using libcrt, and there are no buttons, just keystrokes and function keys. – octopusgrabbus Sep 30 '15 at 15:35
  • @CoryKramer Ok. Sorry – Faminator Sep 30 '15 at 15:36
  • @octopusgrabbus Thank you. Please write this into an answer. I will upvote it – Faminator Sep 30 '15 at 15:37
  • You may find the accepted answer to [Command-line dialog tool for Windows](http://stackoverflow.com/q/553352/4014959) helpful. – PM 2Ring Sep 30 '15 at 15:51

3 Answers3

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.

ergonaut
  • 6,929
  • 1
  • 17
  • 47
  • I can't use it on windows. I am using Windows. – Faminator Sep 30 '15 at 15:28
  • See https://pypi.python.org/pypi/UniCurses, from the more recent topical guide https://docs.python.org/3/howto/curses.html – Filip Dupanović Sep 30 '15 at 15:31
  • You can also read about [tkinter](https://docs.python.org/3.4/library/tkinter.html). I think that some of the controls that you want can't be used in a console (like a button) – aaossa Sep 30 '15 at 15:47
  • @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. – PM 2Ring Sep 30 '15 at 15:54
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.

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
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.

Faminator
  • 888
  • 1
  • 10
  • 16