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

วิธีปิดหน้าต่าง Tkinter โดยกดปุ่ม


ภาพรวม

Tkinter สร้าง Window/Frame ที่มี Widgets และ Labels สมมติต้องการปิดหน้าต่าง Tkinter ด้วยปุ่ม Button เป็น UI Widget ใช้ทำ Operation เฉพาะ

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

# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame
win = Tk()
# Set the geometry of frame
win.geometry("600x250")
# Create a Label
Label(win, text="Press the Close Button to close the window", font=('Helvetica bold', 11)).pack(pady=20)
# Define a function to close the window
def close_win():
    win.destroy()
# Create a Button for closing the window
button = Button(win, text="Close", command=close_win)
button.pack(pady=20)
win.mainloop()

ผลลัพธ์

รันโค้ดจะแสดงหน้าต่างที่มีปุ่ม Trigger ปิดหน้าต่าง/Frame

วิธีปิดหน้าต่าง Tkinter โดยกดปุ่ม

คลิก "Close" เพื่อปิดหน้าต่าง