destroy() method in Tkinter | Python

Tkinter supports a variety of methods to perform various tasks. It also offers some universal method.

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

Syntax:



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

This method can be used with after() method.

Code #1: destroy() method passed as command

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing only those functions
# which are needed
from tkinter import * 
from tkinter.ttk import *
  
# creating tkinter window
root = Tk()
  
# Creating button. In this destroy method is passed
# as command, so as soon as button 1 is pressed root
# window will be destroyed
btn1 = Button(root, text ="Button 1", command = root.destroy)
btn1.pack(pady = 10)
  
# Creating button. In this destroy method is passed
# as command, so as soon as button 2 is pressed
# button 1 will be destroyed
btn2 = Button(root, text ="Button 2", command = btn1.destroy)
btn2.pack(pady = 10)
  
# infinite loop
mainloop()

chevron_right


Output:

As you may observe, in above code that the command that is passed in button-2 is to destroy button-1 so as soon as you press button-2, button-2 will get destroyed.

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing only those functions
# which are needed
from tkinter import * 
from tkinter.ttk import *
  
# creating tkinter window
root = Tk()
  
# Creating button. In this destroy method is passed
# as command, so as soon as button 1 is pressed root
# window will be destroyed
btn1 = Button(root, text ="Button 1")
btn1.pack(pady = 10)
  
# Creating button. In this destroy method is passed
# as command, so as soon as button 2 is pressed
# button 1 will be destroyed
btn2 = Button(root, text ="Button 2")
btn2.pack(pady = 10)
  
# after method destroying button-1
# and button-2 after certain time
btn1.after(3000, btn1.destroy)
btn2.after(6000, btn2.destroy)
  
# infinite loop
mainloop()

chevron_right


Output:
From output you may see that both the widgets are destroyed after a certain time limit and only root window will be left empty.

Note: There is another method available quit() which do not destroy widgets but it exits the tcl/tk interpreter i.e it stops the mainloop().



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.