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

การปรับขนาด Listbox ให้ขยายตามหน้าต่างใน Tkinter

การทำให้ Listbox ขยายเต็มพื้นที่เมื่อ Resize Window ใน Tkinter ทำได้โดยตั้งค่า fill=BOTH และ expand=True ใน pack()

ขั้นตอนการทำงาน

  1. สร้าง Listbox
  2. Pack ด้วย pack(padx=10, pady=10, fill=BOTH, expand=True)
  3. เพิ่มรายการด้วย 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

พารามิเตอร์ค่าผลลัพธ์
fillXขยายแนวนอนเท่านั้น
Yขยายแนวตั้งเท่านั้น
BOTHขยายทั้งสองทิศทาง
NONEไม่ขยาย (ค่าเริ่มต้น)
expandTrueรับพื้นที่ว่างเพิ่มเติม
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, EXTENDED
  • exportselection=False - รักษา Selection ระหว่างหลาย Listbox
  • activestyle: 'underline', 'dotbox', 'none'

การประยุกต์ใช้

เหมาะสำหรับ: File browser, Log viewer, Chat history, Playlist, Any scrollable list ที่ต้องการ Responsive layout