How to insert a temporary text in a tkinter Entry widget?


To insert a temporary text in a tkinter Entry widget, we will bind the <FocusIn> event with the Entry widget and call a user-defined function to delete the text inside the Entry widget.

Steps −

  • Import the tkinter library and create an instance of tkinter frame.

  • Set the size of the frame using geometry method.

  • Create a user-defined method "temp_text()" to capture the <FocusIn> event and delete the temporary text inside the Entry widget.

  • Create an Entry widget inside the Root window and set its properties such as background color, width, and border width.

  • Use the insert() method of the Entry widget to insert a string from the starting location "0". This is the temporary text which will disappear when the Entry widget is in clicked.

  • Bind the <FocusIn> event with the Entry widget and call the temp_text() method.

  • Finally, run the mainloop of the application window.

Example

# Import the required library
from tkinter import *

# Create an instance of tkinter frame
win = Tk()

# Define geometry of the window
win.geometry("700x250")

def temp_text(e):
   textbox.delete(0,"end")

textbox = Entry(win, bg="white", width=50, borderwidth=2)
textbox.insert(0, "This is Temporary Text...")
textbox.pack(pady=20)

textbox.bind("<FocusIn>", temp_text)

win.mainloop()

Output

Upon execution, it will show the following window −

When the user clicks inside the Entry widget, the temporary text will automatically disappear.

Updated on: 26-Oct-2021

18K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements