How to delete Tkinter widgets from a window?

TkinterPythonServer Side ProgrammingProgramming

Sometimes, we want to remove a widget that is of no use in the application. We can delete widgets from the window or frame using the .destroy method in tkinter. It can be invoked in the widget by defining a function for it.

Example

In this example, we have created a button that will remove the text label widget from the window.

#Import the tkinter library
from tkinter import *

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

#Set the geometry
win.geometry("650x450")

#Define a function to remove the text from the screen
def delete_text():
   text.destroy()

#Create a text widget
text= Label(win,text="This is a New Line", font=('Aerial bold', 20))
text.pack(pady=20)

#Create a button for Deleting Widget
Button(win, text= "Click Here", font=('bold',20), command=
delete_text).pack(pady=10)

win.mainloop()

Output

Running the above code will produce the following output −

Now, click the "Click Here" button. It will delete the Label Text widget from the window.

raja
Published on 26-Mar-2021 10:54:21
Advertisements