How to add placeholder to an Entry in tkinter – Python
In this tutorial, we will discuss how to add a placeholder to an entry widget in Tkinter.
A placeholder is nothing more than a hint about what to write on an Entry widget, you might have seen a placeholder username and password in the box to enter details while visiting various sites. When the user has typed nothing, we see a placeholder.
For this, we can start by importing the Tkinter library and then creating a Tkinter object named obj, with the required geometry of 200*200. We will create an entry box then we will place text in the entry box. Using the bind method we will call the function click and leave, click will be called when we click on entry box and leave will be called when we leave the entry box.
Here’s the snippet-
from tkinter import * obj = Tk() obj.geometry('200x200') def click(*args): placeholder.delete(0, 'end') def leave(*args): placeholder.delete(0, 'end') placeholder.insert(0, 'I am placeholder') obj.focus() placeholder = Entry(obj, width=60) placeholder.insert(0, 'Enter Text:- ') placeholder.pack(pady=10) placeholder.bind("<Button-1>", click) placeholder.bind("<Leave>", leave) obj.mainloop()
Here as we can see the desired output, when we click on the entry box the text fades away. This is the sole purpose of placeholder.
Leave a Reply