Tkinter มี Geometry Manager 3 แบบ: pack(), grid(), place() สำหรับการตั้งตำแหน่งแน่นอน (Absolute Positioning) ใช้ place(x, y) ซึ่งระบุพิกัด X, Y ตรงๆ
ตัวอย่างโค้ด: ใช้ place()
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("750x250")
def close_win():
win.destroy()
# ปุ่มตรงกลางด้วย place(x, y)
button = ttk.Button(win, text="Click", command=close_win)
button.place(x=325, y=125)
Label(win, text="Click the Button to Close the Window",
font=('Consolas 15')).pack()
win.mainloop()
เปรียบเทียบ Geometry Managers
| Manager | เหมาะสำหรับ | ข้อดี | ข้อเสีย |
|---|---|---|---|
pack() | Stack widgets แนวตั้ง/แนวนอน | ง่าย, Auto-layout | ควบคุมตำแหน่งยาก |
grid() | Layout แบบตาราง Row/Column | จัดระเบียบง่าย, Responsive | ซับซ้อนกว่า pack |
place() | Absolute/Relative positioning | ควบคุมตำแหน่งแม่นยำ | ไม่ Responsive, Hardcode |
place() แบบ Relative (Responsive)
# Relative to parent size (0.0 - 1.0)
btn.place(relx=0.5, rely=0.5, anchor='center') # กลางจอพอดี
btn.place(relx=0, rely=0, relwidth=1, relheight=1) # เต็มพื้นที่
# ผสม Absolute และ Relative
btn.place(x=10, rely=0.5, anchor='w') # ซ้าย 10px, กลางแนวตั้ง
การจัดกึ่งกลางด้วย grid() (แนะนำกว่า place)
win.grid_rowconfigure(0, weight=1)
win.grid_columnconfigure(0, weight=1)
btn = ttk.Button(win, text="Centered")
btn.grid(row=0, column=0) # อยู่กลางอัตโนมัติเพราะ weight=1
การประยุกต์ใช้ place()
- Overlay widgets (Tooltip, Popup, Loading spinner)
- Watermark / Logo มุมจอ
- Custom drawing canvas controls
- Game UI elements
- Draggable widgets
ข้อควรระวัง
place() ไม่ปรับตัวเมื่อ Resize Window (เว้นแต่ใช้ relative) ควรใช้ grid() หรือ pack() สำหรับ Layout หลัก ใช้ place() เฉพาะ Widget พิเศษ