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

วิธีสร้าง Modal Dialog ใน Tkinter

Modal Dialog เป็นกล่องโต้ตอบที่บังคับให้ผู้ใช้ตอบสนองก่อนจะทำงานอื่นต่อได้ ใน Tkinter สร้างได้โดยใช้ Toplevel widget ซึ่งจะลอยอยู่เหนือหน้าต่างหลัก

ขั้นตอนสร้าง

  1. สร้าง Toplevel window
  2. กำหนดฟังก์ชันสำหรับจัดการเหตุการณ์ (Yes/No)
  3. เพิ่ม widget ต่างๆ ใน Toplevel เช่น Label, Button
  4. กำหนดการทำงานเมื่อผู้ใช้เลือก

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

from tkinter import *
from tkinter import ttk

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

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

def choice(option):
    pop.destroy()
    if option == "yes":
        label.config(text="Hello, How are You?")
    else:
        label.config(text="You have selected No")
        win.destroy()

def click_fun():
    global pop
    pop = Toplevel(win)
    pop.title("Confirmation")
    pop.geometry("300x150")
    pop.config(bg="white")

    Label(pop, text="Would You like to Proceed?", font=('Arial', 12)).pack(pady=20)

    frame = Frame(pop, bg="gray71")
    frame.pack(pady=10)

    Button(frame, text="Yes", command=lambda: choice("yes"), bg="blue", fg="white").grid(row=0, column=1)
    Button(frame, text="No", command=lambda: choice("no"), bg="blue", fg="white").grid(row=0, column=2)

label = Label(win, text="", font=('Arial', 14))
label.pack(pady=40)

ttk.Button(win, text="Click Here", command=click_fun).pack()

win.mainloop()

ผลลัพธ์

หน้าต่างหลักมีปุ่ม "Click Here" เมื่อกดจะแสดง Modal Dialog ให้เลือก Yes/No

วิธีสร้าง Modal Dialog ใน Tkinter

วิธีสร้าง Modal Dialog ใน Tkinter