destroy() method in Tkinter - Python

C++Server Side ProgrammingProgramming

The destroy() method in Tkinter destroys a widget. It is useful in controlling the behavior of various widgets which depend on each other. Also when a process is complete by some user action we need to destroy the GUI components to free the memory as well as clear the screen. The destroy() method achieves all this.

In the below example we have screen with 3 buttons. Clicking the first button closes the window itself where as the clicking of the second button closes the 1st button and so on. This behavior is emulated by using the destroy method as shown in the program below.

Example

from tkinter import *
from tkinter.ttk import *
#tkinter window
base = Tk()

#This button can close the window
button_1 = Button(base, text ="I close the Window", command = base.destroy)
#Exteral paddign for the buttons
button_1.pack(pady = 40)

#This button closes the first button
button_2 = Button(base, text ="I close the first button", command = button_1.destroy)
button_2.pack(pady = 40)

#This button closes the second button
button_3 = Button(base, text ="I close the second button", command = button_2.destroy)
button_3.pack(pady = 40)
mainloop()

Running the above code gives us the following result −

On clicking the various buttons we can observer different behaviors as mentioned in the program.

raja
Published on 19-Dec-2019 16:45:34
Advertisements