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

วิธีผูกปุ่ม Escape ให้ปิดหน้าต่างใน Tkinter

Event binding ใน Tkinter ช่วยให้แอปพลิเคชันตอบสนองต่อการกระทำของผู้ใช้ เช่น การกดปุ่มหรือแป้นพิมพ์ ใช้เมธอด bind('', callback) เพื่อผูกเหตุการณ์กับฟังก์ชัน callback

เพื่อให้กดปุ่ม Esc แล้วปิดหน้าต่าง ให้ผูก event '<Escape>' กับฟังก์ชันที่เรียก win.destroy()

ตัวอย่างโค้ด

from tkinter import *
from tkinter import ttk

win = Tk()
win.geometry("700x350")

style = ttk.Style()
style.theme_use('xpnative')

def close_win(e):
    win.destroy()

label = ttk.Label(win, text="Eat, Sleep, Code and Repeat",
                  font=('Times New Roman italic', 18),
                  background="black", foreground="white")
label.place(relx=.5, rely=.5, anchor=CENTER)

ttk.Label(win, text="Now Press the ESC Key to close this window",
          font=('Arial 11')).pack(pady=10)

# ผูกปุ่ม Escape กับฟังก์ชันปิดหน้าต่าง
win.bind('', lambda e: close_win(e))

win.mainloop()

ผลลัพธ์

หน้าต่างจะปิดทันทีเมื่อกดปุ่ม Esc

วิธีผูกปุ่ม Escape ให้ปิดหน้าต่างใน Tkinter