Tkinter 中的 destroy() 方法——Python
Tkinter 中的 destroy() 方法可銷燬一個構件。它對於控制相互依賴的各種構件的行為非常有用。同樣,當某個程序在使用者操作後完成時,我們需要銷燬 GUI 元件以釋放記憶體以及清除螢幕。destroy() 方法可實現所有這些功能。
在下面的示例中,我們有一個有 3 個按鈕的螢幕。點選第一個按鈕會關閉視窗本身,而點選第二個按鈕會關閉第一個按鈕,依此類推。此行為透過使用 destroy 方法實現,如下面的程式所示。
示例
from tkinter import * from tkinter.ttk import * #tkinter window base = Tk() #This button can close the window button_1 = Button(base, text ="I close the Window", command = base.destroy) #Exteral paddign for the buttons button_1.pack(pady = 40) #This button closes the first button button_2 = Button(base, text ="I close the first button", command = button_1.destroy) button_2.pack(pady = 40) #This button closes the second button button_3 = Button(base, text ="I close the second button", command = button_2.destroy) button_3.pack(pady = 40) mainloop()
執行上面的程式碼會得到以下結果 −
透過點選各個按鈕,我們可以觀察到程式中提到的不同行為。
廣告