当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python Tkinter destroy()用法及代码示例


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

输出:

如您所见,在上面的代码中,在button-2中传递的命令是销毁button-1,因此,一旦您按一下button-2,button-2就会被销毁。

代码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()。



相关用法


注:本文由纯净天空筛选整理自sanjeev2552大神的英文原创作品 destroy() method in Tkinter | Python。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。