在python中的终端中插入输入时更改图标

2024-09-25 08:37:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python在终端中创建一个登录面板,我希望在输入之前动态更改图标,即每当用户填充输入时,图标都会更改

例如:

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

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

我试过:

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

有可能这样做吗?如果是的话,我怎样才能做到呢


Tags: the用户py终端default面板mainline
1条回答
网友
1楼 · 发布于 2024-09-25 08:37:17

我不会告诉你整件事,但是@PranavHosangadi提供的链接是一个很好的资源

似乎您正在使用Windows,因此curses模块无法立即使用。但是,您可以pip install windows-curses获得大部分功能。虽然我注意到一些常量,如curses.KEY_BACKSPACE,在windows版本上有所不同,但您可以对其进行修改,并确定哪些适用于您

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

一些资源:

Official Docs

Some helpful examples 这一部分只有linux的部分,但是经过一些尝试和错误,这些部分是显而易见的

相关问题 更多 >