How to add a placeholder to a record in tkinter?

I created a login window in tkinter, which has two input fields, the first is the username and the second is the password.
the code

from tkinter import * ui = Tk() e1 = Entry(ui) #i need a placeholder "Username" in the above entry field e1.pack() ui.mainloop() 

I need a placeholder called "Username" in Entry , but if you click inside, the text should disappear.

+5
source share
2 answers

You need to set a default value for this entry. Like this:

 from tkinter import * ui = Tk() e1 = Entry(ui) e1.insert(0, 'username') e1.pack() ui.mainloop() 

Then, if you want to delete the content when you click this entry, you need to associate the event with a mouse click using the event handler method to update the contents of this entry. Here is the link for you.

+5
source

You can create a class that inherits from Entry , as shown below:

 import tkinter as tk class EntryWithPlaceholder(tk.Entry): def __init__(self, master=None, placeholder="PLACEHOLDER", color='grey'): super().__init__(master) self.placeholder = placeholder self.placeholder_color = color self.default_fg_color = self['fg'] self.bind("<FocusIn>", self.foc_in) self.bind("<FocusOut>", self.foc_out) self.put_placeholder() def put_placeholder(self): self.insert(0, self.placeholder) self['fg'] = self.placeholder_color def foc_in(self, *args): if self['fg'] == self.placeholder_color: self.delete('0', 'end') self['fg'] = self.default_fg_color def foc_out(self, *args): if not self.get(): self.put_placeholder() if __name__ == "__main__": root = tk.Tk() username = EntryWithPlaceholder(root, "username") password = EntryWithPlaceholder(root, "password", 'blue') username.pack() password.pack() root.mainloop() 
+3
source

Source: https://habr.com/ru/post/1210555/


All Articles