How to clear Text widget content while clicking on the Entry widget itself in Tkinter?


Tkinter Text widget is an Input widget that supports multiline user input. It is also known as Text Editor which allows users to write the content and data in it. The content of the text widget can be cleared by defining the delete(0, END) command. Similarly, we can clear the content by clicking the Entry widget itself. This can be achieved by binding the function with a click event.

Example

#Import the required libraries
from tkinter import *

#Create an instance of Tkinter Frame
win = Tk()

#Set the geometry of Tkinter Frame
win.geometry("700x250")

#Define a function to clear the content of the text widget
def click(event):
   name.configure(state=NORMAL)
   name.delete(0, END)
   name.unbind('<Button-1>', clicked)

#Create a Label widget
label = Label(win, text= "Enter Your Name", font= ('Helvetica 13 bold'))
label.pack(pady= 10)

#Create an Entry widget
name = Entry(win, width=45)
name.insert(0, 'Enter Your Name Here...')
name.pack(pady=10)

#Bind the Entry widget with Mouse Button to clear the content
clicked = name.bind('<Button-1>', click)
win.mainloop()

Output

Running the above code will display a window with an Entry widget.

When we click the Entry field, it will clear its content automatically.

Updated on: 26-May-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements