How to clear the Entry widget after a button is pressed in Tkinter?

TkinterPythonServer Side ProgrammingProgramming

Tkinter Entry widgets are used to display a single line text that is generally taken in the form of user Input. We can clear the content of Entry widget by defining a method delete(0, END) which aims to clear all the content in the range. The method can be invoked by defining a function which can be used by creating a Button Object.

Example

In this example, we have created an entry widget and a button that can be used to clear all the content from the widget.

#Import the required libraries
from tkinter import *

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

#Set the geometry of frame
win.geometry("650x250")

#Define a function to clear the Entry Widget Content
def clear_text():
   text.delete(0, END)

#Create a entry widget
text= Entry(win, width=40)
text.pack()

#Create a button to clear the Entry Widget
Button(win,text="Clear", command=clear_text, font=('Helvetica bold',10)).pack(pady=5)

win.mainloop()

Output

Running the above code will display a window that contains an entry widget and a Button which can be used to clear the text written in the entry field.

Now click on the “Clear” Button to clear the Entry widget.

raja
Published on 26-Mar-2021 11:06:33
Advertisements