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

วิธีออกจากโปรแกรม Python ด้วยปุ่ม Tkinter Button

เพื่อออกจากโปรแกรม Python ด้วยปุ่ม Tkinter ให้ทำตามขั้นตอนด้านล่าง

ขั้นตอน

  • นำเข้า tkinter และสร้าง instance ของ tkinter frame

  • กำหนดขนาด frame ด้วย geometry

  • กำหนดฟังก์ชัน close() เพื่อปิดหน้าต่าง เรียก win.destroy() ภายใน close()

  • สร้างปุ่มเรียกฟังก์ชัน close()

  • รัน mainloop

ตัวอย่าง

from tkinter import *

win = Tk()
win.geometry("700x350")
win.title("Click the Button to Close the Window")

def close():
    # win.destroy()
    win.quit()

Button(win, text="Close the Window", font=("Calibri", 14, "bold"), command=close).pack(pady=20)

win.mainloop()

ผลลัพธ์

วิธีออกจากโปรแกรม Python ด้วยปุ่ม Tkinter Button

คลิกปุ่มจะปิดหน้าต่าง

แทน win.destroy() สามารถใช้ win.quit() ได้ แต่มีความแตกต่างเล็กน้อย: win.quit() ออกจากแอปพลิเคชันทันที (mainloop ยังทำงานในพื้นหลัง) ส่วน win.destroy() จะยกเลิก mainloop และทำลาย widget ทั้งหมดในหน้าต่าง