การสร้างหน้าต่างลูก (Child Window / Popup / Dialog) ใน Tkinter ใช้ Toplevel(parent) ไม่ใช่ Tk() เพราะ Tk() ต้องมีเพียงตัวเดียวต่อโปรแกรม
ขั้นตอนการทำงาน
- สร้าง Root Window (
Tk()) - สร้างปุ่มที่เรียกฟังก์ชันเปิดหน้าต่างใหม่
- ในฟังก์ชัน: สร้าง
Toplevel(root), ตั้งค่า Geometry, Title - เพิ่ม Widget ใน Child Window
- (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/Title | Default 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