Modifica dell'icona all'inserimento dell'input nel terminale in python
Sto creando un pannello di login nel terminale in python e voglio cambiare dinamicamente l'icona prima dell'input, cioè ogni volta che l'utente riempie l'input l'icona cambia.
Esempio:
F:\command_line>python main.py
? username: # initially there is a question mark.
✓ username: # If the user fills the username the icon changes to ✓
Provai:
default = '?'
onChange = '✓'
inp = input(default + " " + name + ":")
# I can't figure out how I can change it
È possibile farlo? In caso affermativo, come posso ottenerlo?
Risposte
Non ti guiderò attraverso l'intera cosa, ma il link fornito da @PranavHosangadi è una buona risorsa.
Sembra che tu stia utilizzando Windows, quindi il cursesmodulo non è immediatamente disponibile. Tuttavia puoi pip install windows-cursesottenere la maggior parte delle funzionalità. Anche se ho notato che alcune delle costanti come curses.KEY_BACKSPACEdifferiscono nella versione per Windows, ma puoi giocherellarci e determinare cosa funziona per te.
# 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)
Alcune risorse:
Documenti ufficiali
Alcuni esempi utili Questo ha alcuni pezzi solo per Linux, ma con alcuni tentativi ed errori, quelle parti sono evidenti.