I have created a login window in tkinter which has two Entry field, first one is Username and second one is Password.
code
from tkinter import * ui = Tk() e1 = Entry(ui) #i need a placeholder "Username" in the above entry field e1.pack() ui.mainloop()
I want a placeholder called "Username" in the Entry
, but if you click inside the entry box, the text should disappear.
In Python, you can use {} as placeholders for strings and use format() to fill in the placeholder with string literals. For example: print("You have {} apples.". format(5)) # this will print: # You have 5 apples.
Basically, the __init__ method of a class is called as soon as an instance of that class is created. An example of the instance being created in your code is : app = Application(master=root) this means that your class must be called 'Application' though you haven't included that part.
pack is the easiest layout manager to use with Tkinter. Instead of declaring the precise location of a widget, pack() declares the positioning of widgets in relation to each other. However, pack() is limited in precision compared to place() and grid() which feature absolute positioning.
You can create a class that inherits from Entry
like 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()
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 the entry, then you have to bind a mouse click event with an event handler method to update content of this entry. Here is a link for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With