เมธอด destroy() ใน Tkinter ทำลายวิดเจ็ต มันมีประโยชน์ในการควบคุมพฤติกรรมของวิดเจ็ตต่างๆ ที่ขึ้นอยู่กับกัน รวมถึงเมื่อกระบวนการเสร็จสิ้นโดยการกระทำของผู้ใช้ เราจำเป็นต้องทำลายส่วนประกอบ 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) # External padding 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()
การรันโค้ดข้างต้นจะให้ผลลัพธ์ดังนี้:
เมื่อคลิกปุ่มต่างๆ เราสามารถสังเกตพฤติกรรมที่แตกต่างกันได้ตามที่ระบุในโปรแกรม
