Search code examples
pythonpython-3.xtkinterpasswords

Python's tkinter smart entry password


I want to create a password entry.

One easy solution is:

password = Entry(root, font="Verdana 22")
password.config(show="*");

but the problem is that to avoid typos, I want to show the item clicked to be visible only for a few seconds, while everything else is hidden. After a few seconds everything is hidden.


Solution

  • It's not easy to do exactly what you want with Tkinter, but here's something close: when you press a key it displays the whole contents of the Entry, but after one second the text is hidden again.

    I developed this on Python 2; to use it on Python 3 change Tkinter to tkinter.

    import Tkinter as tk
    
    class PasswordTest(object):
        ''' Password Entry Demo '''
        def __init__(self):
            root = tk.Tk()
            root.title("Password Entry Demo")
    
            self.entry = e = tk.Entry(root)
            e.pack()
            e.bind("<Key>", self.entry_cb)
    
            b = tk.Button(root, text="show", command=self.button_cb)
            b.pack()
    
            root.mainloop()
    
        def entry_cb(self, event):
            #print(`event.char`, event.keycode, event.keysym )
            self.entry.config(show='')
            #Hide text after 1000 milliseconds
            self.entry.after(1000, lambda: self.entry.config(show='*'))
    
        def button_cb(self):
            print('Contents:', repr(self.entry.get()))
    
    PasswordTest()
    

    It would be tricky to only display the last char entered. You'd have to modify the displayed string manually while maintaining the real password string in a separate variable and that's a bit fiddly because the user can move the insertion point cursor at any time.

    On a final note, I really don't recommend doing anything like this. Keep passwords hidden at all times! If you want to reduce the chance of typos in newly-chosen passwords, the usual practice is to make the user enter the password twice.