简体   繁体   中英

how to hide password input on placeholder entry in python tkinter

I want a placeholder entry that is done by the below code. but I need the input password which would be hidden from the user (which may be in the form of asterisks.)

from tkinter import *

root=Tk()
root.geometry("300x200+600+250")
root.config(background="#E0FFFF")
root.resizable(False,False)


def userText(event):
    e1.delete(0,END)
    usercheck=True

def passText(event):
    e2.delete(0, END)
    passcheck=True



a=StringVar()
b=StringVar()
usercheck=False
passcheck=False


Label(root,text="User name",bg="#E0FFFF").place(x=20,y=50)
e1= Entry(root,textvariable=a)
e1.place(x=100,y=50)
e1.insert(0,"Enter username")
e1.bind("<Button>",userText)

Label(root,text="Password",bg="#E0FFFF").place(x=20,y=95)
e2= Entry(root,textvariable=b)
e2.place(x=100,y=95)
e2.insert(0,"Enter password")
e2.bind("<Button>",passText)


root.mainloop()

Extended tkinter.Entry showing placeholder text and * on a password entry.


import tkinter as tk


class Entry(tk.Entry):
    def __init__(self, master, placeholder):
        super().__init__(master)

        self.placeholder = placeholder
        self._is_password = True if placeholder == "password" else False

        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<FocusOut>", self.on_focus_out)

        self._state = 'placeholder'
        self.insert(0, self.placeholder)

    def on_focus_in(self, event):
        if self._is_password:
          self.configure(show='*')

        if self._state == 'placeholder':
            self._state = ''
            self.delete('0', 'end')

    def on_focus_out(self, event):
        if not self.get():
          if self._is_password:
            self.configure(show='')

          self._state = 'placeholder'
          self.insert(0, self.placeholder)

Usage:

if __name__ == "__main__": 
    root = tk.Tk() 

    username = Entry(root, "username")
    username.pack()

    password = Entry(root, "password")
    password.pack()  

    root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM