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

การตั้งตำแหน่งปุ่ม (Button Position) ใน Tkinter Python

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 พิเศษ