Cambio de icono al insertar entrada en terminal en Python

Aug 27 2020

Estoy creando un panel de inicio de sesión en el terminal en Python y quiero cambiar dinámicamente el icono antes de la entrada, es decir, cada vez que el usuario completa la entrada, el icono cambia.

Ejemplo:

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

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

Lo intenté:

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

¿Es posible hacer esto? Si es así, ¿cómo puedo lograrlo?

Respuestas

Axe319 Aug 27 2020 at 02:10

No lo guiaré a través de todo, pero el enlace que proporcionó @PranavHosangadi es un buen recurso.

Parece que está usando Windows, por lo que el cursesmódulo no está disponible de inmediato. Sin embargo, puede pip install windows-cursesobtener la mayor parte de la funcionalidad. Aunque he notado que algunas de las constantes curses.KEY_BACKSPACEdifieren en la versión de Windows, pero puede jugar con ellas y determinar qué funciona para usted.

# 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)

Algunos recursos:

Documentos oficiales

Algunos ejemplos útiles Este tiene algunas piezas solo para Linux, pero con algunas pruebas y errores, esas partes son evidentes.