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

สร้าง Custom Popup Dialog Box ใน Tkinter

MessageBox มาตรฐานปรับแต่งไม่ได้ สร้าง Custom Dialog เองด้วย Toplevel widget

ขั้นตอน

  1. สร้างปุ่มเปิด dialog
  2. ฟังก์ชันสร้าง Toplevel window
  3. เพิ่ม Label, Button (Yes/No) ใน Toplevel
  4. กำหนด callback สำหรับแต่ละปุ่ม

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

from tkinter import *
from tkinter import ttk

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

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

def click_fun():
    global pop
    pop = Toplevel(win)
    pop.title("Confirmation")
    pop.geometry("700x250")
    pop.config(bg="green3")

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

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

    Button(frame, text="Yes", command=lambda: choice("yes"), bg="green").grid(row=0, column=1)
    Button(frame, text="No", command=lambda: choice("no"), bg="green").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 → แสดง Custom Dialog → เลือก Yes/No → อัปเดตข้อความหน้าต่างหลัก

สร้าง Custom Popup Dialog Box ใน Tkinter

สร้าง Custom Popup Dialog Box ใน Tkinter