Horje
How to Clear the Entry Widget After Button Press in Tkinter

The entry widget in Tkinter is a common input field that allows users to enter and edit a single line of text. Clearing the contents of this widget programmatically can enhance user interaction, especially after submitting or resetting a form. In this article, we will explore two different approaches to clear the entry after a button is pressed in the Tkinter.

Clear The Entry Widget After A Button Is Pressed In Tkinter

Let us see a few different approaches to clear the entry after a button is pressed in the Tkinter.

  • Using the delete Method
  • Using the StringVar Class

Clear the Entry Widget After a Button Press in Tkinter Using the delete Method

In this example, we are using the delete method to clear the contents of the Entry widget when the button is pressed. The delete method removes the text from position 0 to tk.END, effectively clearing the entry field.

Python
import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

entry = tk.Entry(root, font=("Helvetica", 14))
entry.pack(pady=20)

clear_button = tk.Button(root, text="Clear Entry", font=("Helvetica", 14))
clear_button.pack(pady=20)

clear_button.config(command=lambda: entry.delete(0, tk.END))

root.mainloop()

Output:

1

Clear the Entry Widget After a Button Press in Tkinter Using the StringVar Class

In this example, we are using the StringVar class to manage the value of the Entry widget. When the button is pressed, the set method of StringVar is called with an empty string, which clears the contents of the entry field.

Python
import tkinter as tk

root = tk.Tk()
root.geometry("300x200")

entry_var = tk.StringVar()
entry = tk.Entry(root, textvariable=entry_var, font=("Helvetica", 14))
entry.pack(pady=20)

clear_button = tk.Button(root, text="Clear Entry", font=("Helvetica", 14))
clear_button.pack(pady=20)

clear_button.config(command=lambda: entry_var.set(""))

root.mainloop()

Output:

2





Reffered: https://www.geeksforgeeks.org


Python

Related
How to Build a basic Iterator in Python? How to Build a basic Iterator in Python?
How to Change the name of a key in dictionary? How to Change the name of a key in dictionary?
How to Disable Output Buffering in Python How to Disable Output Buffering in Python
Rendering 3D Surfaces Using Parametric Equations in Python Rendering 3D Surfaces Using Parametric Equations in Python
Define Custom Exceptions in Python Define Custom Exceptions in Python

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18