Search code examples
pythonpython-3.x

How to change the text being inputted turn to '*' in python?


how do I change the text to * while it is being inputted, like:

#Think that the code below is running in the console and I am 
#inputting in it

Password: Example # How do make it turn it to '*******' while it is still being written?

Yup, i am not forced to only input, I can type in any command, please just tell me how to.

And you can tell tk code too


Solution

  • For tkinter entry, use the option show. Here is a code:

    import tkinter as tk
    root = tk.Tk()
    passw = tk.Entry(root,show="*")
    passw.grid(row=0,column=0)
    passb = tk.Button(root,text="Print Password",command=lambda :print(passw.get()))
    passb.grid(row=1,column=0)
    root.mainloop()
    

    To get password in console, you will have to modify the module getpass (Try at your own risk). Go to your python folder and open folder Lib. Open the file getpass.py and go to line 98 (there will be a function naming win_getpass)
    Replace the whole function (win_getpass) with (lines:98-119) (Updated):

    def win_getpass(prompt='Password: ', stream=None,show=""):
        """Prompt for password with echo off, using Windows getch()."""
        if sys.stdin is not sys.__stdin__:
            return fallback_getpass(prompt, stream)
    
        for c in prompt:
            msvcrt.putwch(c)
        pw = ""
        while True:
            c = msvcrt.getwch()
            if c == '\r' or c == '\n':
                break
            if c == '\003':
                raise KeyboardInterrupt
            if c == '\b':
                pw = pw[:-1]
                if pw != "":msvcrt.putwch("\b");msvcrt.putwch(" ");msvcrt.putwch("\b")
            else:
                pw = pw + c
                msvcrt.putwch(show)
        msvcrt.putwch('\r')
        msvcrt.putwch('\n')
        return pw
    

    Now you can use the getpass function as:

    import getpass
    getpass.getpass("Enter your password: ",show="*")
    

    You can change the value of show to whatever you want to show. Default is empty (means hide).

    Note:

    getpass will only work in console. It will raise error in IDLE.

    Screenshot:

    console