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

วิธีจัดตำแหน่งปุ่ม (Button) บนหน้าต่าง Tkinter

เพื่อตั้งตำแหน่งปุ่ม ใช้เมธอด place ของ button widget รับพิกัด x และ y ของปุ่ม

ขั้นตอน

  • นำเข้าไลบรารี สร้าง instance ของ tkinter frame

  • กำหนดขนาด frame ด้วย win.geometry

  • สร้างปุ่มหลายตัว ชื่อ "Button-1", "Button-2" เป็นต้น

  • ตั้งตำแหน่งปุ่มด้วย place method ส่งพิกัด x และ y

  • รัน mainloop

ตัวอย่าง

from tkinter import *
from tkinter import ttk

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

button = ttk.Button(win, text="Button-1")
button.place(x=325, y=125)

button = ttk.Button(win, text="Button-2")
button.place(x=325, y=175)

button = ttk.Button(win, text="Button-3")
button.place(x=325, y=225)

Label(win, text="Position the Buttons", font='Consolas 15').pack()

win.mainloop()

ผลลัพธ์

วิธีจัดตำแหน่งปุ่ม (Button) บนหน้าต่าง Tkinter

สังเกตว่าตัวแปร x คงที่ที่ 325 ทำให้ปุ่มจัดแนวตั้งตรงกัน สามารถเปลี่ยนค่า (x, y) ใน place method เพื่อเปลี่ยนตำแหน่งปุ่ม