Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีจัดการ Event ปิดหน้าต่างใน Tkinter


ภาพรวม

Tkinter มี Custom Handler ปิดหน้าต่าง ทำงานเป็น Callback Function ที่ User รันเพื่อปิดหน้าต่าง ใช้เมธอด destroy() ปิดหน้าต่างทันทีหลังเรียกใน Function หรือ Widget ใดๆ เรียกใช้ Close Event Handler โดยนิยาม Method

ใช้เป็น Argument ใน Widget

# Importing the required library
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the geometry
win.geometry("600x400")
# Create a button and pass arguments in command as a function name
my_button = Button(win, text="X", font=('Helvetica bold', 20), borderwidth=2, command=win.destroy)
my_button.pack(pady=20)
win.mainloop()

เรียกใช้ใน Function

# Importing the required library
from tkinter import *
# Create an instance of tkinter frame or window
win = Tk()
# Set the geometry
win.geometry("600x300")
# Define a function
def close():
    win.destroy()
# Create a button and pass arguments in command as a function name
my_button = Button(win, text="X", font=('Helvetica bold', 20), borderwidth=2, command=close)
my_button.pack(pady=20)
win.mainloop()

ผลลัพธ์

รันโค้ดจะสร้างปุ่ม "X" คลิกเพื่อปิดหน้าต่างหลัก

วิธีจัดการ Event ปิดหน้าต่างใน Tkinter