Alterar ícone ao inserir entrada no terminal em python

Aug 27 2020

Estou criando um painel de login no terminal em python e quero alterar dinamicamente o ícone antes da entrada, ou seja, sempre que o usuário preencher a entrada, o ícone muda.

Exemplo:

F:\command_line>python main.py
?  username: # initially there is a question mark.

✓ username: # If the user fills the username the icon changes to ✓

Eu tentei:

default = '?'
onChange = '✓'
inp = input(default + " " + name + ":")
# I can't figure out how I can change it

É possível fazer isso? Se sim, como posso conseguir isso?

Respostas

Axe319 Aug 27 2020 at 02:10

Não vou explicar tudo, mas o link fornecido por @PranavHosangadi é um bom recurso.

Parece que você está usando o Windows, então o cursesmódulo não está imediatamente disponível para você. No entanto, você pode pip install windows-cursesobter a maior parte da funcionalidade. Embora eu tenha percebido que algumas das constantes como curses.KEY_BACKSPACEdiferem na versão do Windows, você pode mexer com isso e determinar o que funciona para você.

# The module you'll use
import curses

# this is the char value that backspace returns on windows
BACKSPACE = 8

# our main function
def main(stdscr):
    # this is just to initialize the input position
    inp = '? Username:'
    stdscr.addstr(1, 1, inp)
    
    # The input from the user will be assigned to 
    # this variable
    current = ''
    # our main method of obtaining user input
    # it essentially returns control after the 
    # user inputs a character
    # the return value is essentially what ord(char) returns
    # to get the actual character you can use chr(char)
    k = stdscr.getch()

    # break the loop when the x key is pressed
    while chr(k) != 'x':
        # remove characters for backspace presses
        if k == BACKSPACE:
            if len(current):
                current = current[:len(current) - 1]
        # only allow a max of 8 characters
        elif len(current) < 8:
            current = current + chr(k)
        
        # when 8 characters are entered, change the sign
        if len(current) == 8:
            inp = '! Username:'
        else:
            inp = '? Username:'
        
        # not clearing the screen leaves old characters in place
        stdscr.clear()
        # this enters the input on row 1, column 1
        stdscr.addstr(1, 1, inp + current)
        
        # get the next user input character
        k = stdscr.getch()

if __name__ == '__main__':
    # our function needs to be driven by curses.wrapper
    curses.wrapper(main)

Alguns recursos:

Documentos Oficiais

Alguns exemplos úteis Este tem algumas partes apenas para Linux, mas com algumas tentativas e erros, essas partes são aparentes.