Mengubah ikon saat memasukkan input ke terminal dengan python

Aug 27 2020

Saya membuat panel login di terminal dengan python dan saya ingin mengubah ikon secara dinamis sebelum memasukkan, yaitu setiap kali pengguna mengisi masukan, ikon berubah.

Contoh:

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

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

Saya mencoba:

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

Apakah mungkin melakukan ini? Jika ya, Bagaimana cara mencapainya?

Jawaban

Axe319 Aug 27 2020 at 02:10

Saya tidak akan memandu Anda melalui semuanya tetapi tautan yang disediakan @PranavHosangadi adalah sumber yang bagus.

Sepertinya Anda menggunakan Windows sehingga cursesmodul tidak segera tersedia untuk Anda. Namun Anda bisa pip install windows-cursesmendapatkan sebagian besar fungsinya. Meskipun saya telah memperhatikan beberapa konstanta seperti curses.KEY_BACKSPACEberbeda pada versi windows tetapi Anda dapat mengutak-atiknya dan menentukan apa yang berhasil untuk Anda.

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

Beberapa sumber:

Dokumen Resmi

Beberapa contoh berguna Yang satu ini memiliki beberapa bagian khusus linux, tetapi dengan beberapa percobaan dan kesalahan, bagian-bagian itu terlihat jelas.