模糊用户输入

时间:2016-11-17 20:14:57

标签: python input

我正在尝试创建一个程序来接受用户输入,而不是显示实际输入我想用*替换输入

我已尝试使用此代码,但我一直收到以下错误,感谢任何指导或帮助。

import msvcrt
import sys


def userinput(prompt='>'):
    write = sys.stdout.write
    for x in prompt:
        msvcrt.putch(x)

    entry = ""

    while 1:
        x = msvcrt.getch()
        print(repr(x))

        if x == '\r' or x == '\n':
            break
        if x == '\b':
            entry = entry[:-1]
        else:
            write('*')
            entry = entry + x
    return entry

userEntry = userinput()

错误:

Traceback (most recent call last):
  File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 24, in <module>
    userEntry = userinput()
  File "C:\Users\Mehdi\Documents\Teaching\KS5\AS CS\getPass.py", line 9, in userinput
    msvcrt.putch(x)
TypeError: putch() argument must be a byte string of length 1, not str

2 个答案:

答案 0 :(得分:0)

您可以使用Tkinter模块获取用户输入。 这是代码

    from tkinter import *
    root = Tk()
    entry = Entry(root)
    entry.pack()
    entry.config(show='*')
    userinput = entry.get()

您可以将config函数中的'*'替换为所需的任何符号。用户输入的值存储在entry.get()函数中,您应该另存为变量。 在此之前放置打印语句,以便他们知道您要他们在条目中输入什么。或者,您也可以在输入条目之前先做

   label = Label(root, text='Input the text here')
   label.pack()

答案 1 :(得分:-1)

根据您获得的错误,putch获取一个字节,而不是字符串,因此请使用

for x in prompt:
    msvcrt.putch(x.encode()[:1])

[:1]通常不是必需的,只是为了确保字节数组的长度为1根据需要)

比使用流更常见的做法是使用msvcrt.getch并循环直到获得换行符,同时每次打印一个用户输入长度为*的字符串并打印到同一行通过回车结束时的回车功能:

import msvcrt

def getch():
    return chr(msvcrt.getch()[0])

def hidden_input (input_message = 'enter input:'):

    user_input = ''
    new_ch = ''

    while new_ch != '\r':
        print(input_message, '*' * len(user_input), ' ' * 20, end = '\r')
        user_input = user_input[:-1] if new_ch == '\b' else user_input + new_ch 
        new_ch = getch()

    return user_input

hidden_input()