การทำให้ Listbox ขยายเต็มพื้นที่เมื่อ Resize Window ใน Tkinter ทำได้โดยตั้งค่า fill=BOTH และ expand=True ใน pack()
ขั้นตอนการทำงาน
- สร้าง Listbox
- Pack ด้วย
pack(padx=10, pady=10, fill=BOTH, expand=True) - เพิ่มรายการด้วย
insert()
ตัวอย่างโค้ด
from tkinter import *
win = Tk()
win.geometry("750x350")
listbox = Listbox(win)
listbox.pack(padx=10, pady=10, fill=BOTH, expand=True)
# fill=BOTH = ขยายทั้งแนวนอนและแนวตั้ง
# expand=True = ขยายในพื้นที่ว่างที่เหลือ
items = ["Python", "Java", "C++", "Rust", "GoLang", "C#", "JavaScript", "R", "Php"]
for i, item in enumerate(items, 1):
listbox.insert(i, item)
win.mainloop()
คำอธิบาย fill และ expand
| พารามิเตอร์ | ค่า | ผลลัพธ์ |
|---|---|---|
fill | X | ขยายแนวนอนเท่านั้น |
Y | ขยายแนวตั้งเท่านั้น | |
BOTH | ขยายทั้งสองทิศทาง | |
NONE | ไม่ขยาย (ค่าเริ่มต้น) | |
expand | True | รับพื้นที่ว่างเพิ่มเติม |
False | ไม่รับพื้นที่ว่าง (ค่าเริ่มต้น) |
การเพิ่ม Scrollbar
listbox = Listbox(win)
scrollbar = Scrollbar(win, orient=VERTICAL, command=listbox.yview)
listbox.configure(yscrollcommand=scrollbar.set)
listbox.pack(side=LEFT, fill=BOTH, expand=True)
scrollbar.pack(side=RIGHT, fill=Y)
การใช้ grid() แทน pack()
win.grid_rowconfigure(0, weight=1)
win.grid_columnconfigure(0, weight=1)
listbox = Listbox(win)
listbox.grid(row=0, column=0, sticky='nsew', padx=10, pady=10)
scrollbar = Scrollbar(win, orient=VERTICAL, command=listbox.yview)
scrollbar.grid(row=0, column=1, sticky='ns')
listbox.configure(yscrollcommand=scrollbar.set)
Listbox Options สำคัญ
selectmode:SINGLE,BROWSE,MULTIPLE,EXTENDEDexportselection=False- รักษา Selection ระหว่างหลาย Listboxactivestyle:'underline','dotbox','none'
การประยุกต์ใช้
เหมาะสำหรับ: File browser, Log viewer, Chat history, Playlist, Any scrollable list ที่ต้องการ Responsive layout