📜  Tkinter 中的destroy() 方法| Python

📅  最后修改于: 2022-05-13 01:54:25.966000             🧑  作者: Mango

Tkinter 中的destroy() 方法| Python

Tkinter 支持多种方法来执行各种任务。它还提供了一些通用方法。

destroy()是一种通用的小部件方法,即我们可以将此方法与任何可用的小部件以及主 tkinter 窗口一起使用。

句法:

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

此方法可以与 after() 方法一起使用。

代码 #1: destroy() 方法作为命令传递

# 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()

输出:
Tkinter 中的 destroy() 方法

正如您可能观察到的,在上面的代码中,在 button-2 中传递的命令是销毁 button-1,因此只要您按下 button-2,button-2 就会被销毁。
destroy() 方法作为命令传递

代码 #2: destroy() 方法和 after() 方法

# 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()

输出:
从输出中您可能会看到两个小部件在一定时间限制后都被销毁,并且只有根窗口将被留空。

注意:还有另一种可用的方法quit()不会破坏小部件,但它会退出 tcl/tk 解释器,即它会停止mainloop()