【问题标题】:Changing icon on inserting input in terminal in python在 python 的终端中插入输入时更改图标
【发布时间】:2020-12-15 10:32:20
【问题描述】:

我正在 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

可以这样做吗?如果是这样,我该如何实现?

【问题讨论】:

  • 在输入或用户键入任何键时会改变吗?
  • 不,不是@PranavHosangadi
  • 输入时更改。 @MZ
  • @Zodiac,这个问题提供了一种处理终端的标准方法。您需要使用该库来做您想做的事。在你的编程生涯中,你不会在网上找到你需要的确切代码,这似乎就是其中之一。或者,这肯定会回答您的问题。 stackoverflow.com/a/11474509/843953

标签: python python-3.x shell input command-line


【解决方案1】:

我不会带您了解整个过程,但@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 的部分,但经过一些试验和错误,这些部分是显而易见的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-29
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    相关资源
    最近更新 更多