當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。