destroy () method in Tkinter | python

Python Methods and Functions

destroy() — it is a generic widget method, i.e. we can use this method with any of the available widgets as well as the main tkinter window.

Syntax :

 widget_object = Widget (parent, command = widget_class_object .destroy) 

This method can be used with the

# only import these functions
# which are needed

from tkinter import *  

from tkinter.ttk import *

 
# create a tkinter window

root = Tk ()

  
# Create a button. In this, the destroy method is passed
# as a command, since only button 1 is pressed by root
# window will be destroyed

btn1 = Button (root , text = "Button 1" , command = root.destroy)

btn1.pack (pady = 10 )

 
# Create a button. In this, the destroy method is passed
# as a command, since only button 2 is pressed
# button 1 will be destroyed

btn2 = Button (root , text = "Button 2" , command = btn1.destroy)

btn2.pack (pady = 10 )

 
# endless loop
mainloop ()

Output:

As you can see in the above code, the command passed to the cno pku-2 should destroy button-1, so as soon as you press button-2, button-2 will be destroyed. 

Code # 2: destroy () method with after method ()

# import only these functions
# which are needed

from tkinter import *  

from tkinter.ttk import *

 
# create a tkinter window

root = Tk ()

 
# Create a button. In this, the destroy method is passed
# as a command, since only button 1 is pressed by root
# window will be destroyed

btn1 = Button (root , text = "Button 1" )

btn1.pack (pady = 10 )

 
# Create a button. In this, the destroy method is passed
# as a command, since only button 2 is pressed
# button 1 will be destroyed

btn2 = Button (root , text = "Button 2" )

btn2.pack (pady = 10 )

 
# after the button-1 method is destroyed
# and button-2 after a certain time

btn1.after ( 3000 , btn1.destroy)

btn2.after ( 6000 , btn2.destroy)

  
# endless loop
mainloop ()

Output:
From the output you can see that both widgets are destroyed after a certain period of time, and only the root window will remain empty.

Note: there is another method available quit () which does not kill the widgets, but exits the tcl / tk interpreter, i.e. stops mainloop () .





Tutorials