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

การเปิดหน้าต่างใหม่ (Child Window) ด้วยปุ่มใน Tkinter GUI

การสร้างหน้าต่างลูก (Child Window / Popup / Dialog) ใน Tkinter ใช้ Toplevel(parent) ไม่ใช่ Tk() เพราะ Tk() ต้องมีเพียงตัวเดียวต่อโปรแกรม

ขั้นตอนการทำงาน

  1. สร้าง Root Window (Tk())
  2. สร้างปุ่มที่เรียกฟังก์ชันเปิดหน้าต่างใหม่
  3. ในฟังก์ชัน: สร้าง Toplevel(root), ตั้งค่า Geometry, Title
  4. เพิ่ม Widget ใน Child Window
  5. (Optional) win.withdraw() ซ่อน Parent, win.deiconify() แสดงกลับ

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


from tkinter import *
from tkinter import ttk

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

def open_win():
    new = Toplevel(win)
    new.geometry("750x250")
    new.title("New Window")
    Label(new, text="Hey, Howdy?", font=('Helvetica 17 bold')).pack(pady=30)
    # win.withdraw()  # ซ่อน Parent (ถ้าต้องการ)

Label(win, text="Click the below button to Open a New Window",
      font=('Helvetica 17 bold')).pack(pady=30)

ttk.Button(win, text="Open", command=open_win).pack()

win.mainloop()

Toplevel vs Tk()

คุณสมบัติTk()Toplevel()
จำนวนต่อโปรแกรม1 เท่านั้นหลายตัวได้
Parentไม่มี (Root)มี Parent (Owner)
Event Loopรัน mainloop()ใช้ mainloop ของ Root
Icon/TitleDefault Tk Iconสืบทอดจาก Parent (ปรับได้)
Destroyจบโปรแกรมปิดหน้าต่างนั้นอย่างเดียว

Modal Dialog (บังคับโฟกัส)


def open_modal():
    dialog = Toplevel(win)
    dialog.title("Modal Dialog")
    dialog.geometry("300x150")
    dialog.transient(win)      # ตั้ง Owner
    dialog.grab_set()          # Modal: บล็อก Parent
    Label(dialog, text="This is Modal!").pack(pady=20)
    ttk.Button(dialog, text="OK", command=dialog.destroy).pack()
    win.wait_window(dialog)    # รอจนกว่าจะปิด
    print("Dialog closed")

การสื่อสาร Parent-Child


def open_win():
    child = Toplevel(win)
    # อ่านค่าจาก Parent
    value = entry.get()
    Label(child, text=f"From Parent: {value}").pack()
    
    # ส่งค่ากลับ Parent
    def send_back():
        result_var.set(entry_child.get())
        child.destroy()
    
    entry_child = Entry(child)
    entry_child.pack()
    ttk.Button(child, text="Send to Parent", command=send_back).pack()

result_var = StringVar()
entry = Entry(win, textvariable=result_var)
entry.pack()

การประยุกต์ใช้

Settings Dialog, About Box, File Open/Save Dialog, Confirmation Dialog, Tool Palette, Inspector Window, Multi-window App