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

TkinterPythonGUI-Programming

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.

raja
Published on 26-May-2021 12:08:20
Advertisements