การสร้างแอปพลิเคชันด้วย Tkinter นั้นง่าย แต่บางครั้งปิดหน้าต่างหรือ Frame โดยไม่กดปุ่มบน Title Bar อาจยาก ในกรณีเช่นนี้ เราสามารถใช้เมธอด .destroy() เพื่อปิดหน้าต่าง
เนื่องจากแอตทริบิวต์ของ Tkinter เป็นอิสระต่อกัน เราสามารถสร้างเมธอดแยกต่างหากเพื่อปิดหน้าต่างโดยใช้ปุ่ม
ตัวอย่าง
# Import the library
from tkinter import *
# Create an instance of window
win = Tk()
# Set the geometry of the window
win.geometry("700x400")
# Define a function to close the window
def close_win():
win.destroy()
# Create a label
Label(win, text="Click the button to Close the window", font=('Poppins bold', 25)).pack(pady=20)
# Create a Button
Button(win, text="Close", font=('Poppins bold', 16), command=close_win).pack(pady=20)
win.mainloop()
ผลลัพธ์
หากเรารันโค้ดข้างต้น จะผลิตหน้าต่างผลลัพธ์ดังนี้:
