如何調整 Tkinter 列表框以適應內容?


Tkinter 提供了 Listbox 元件,在以列表形式表示大型資料集時非常有用。要配置 listbox 元件,我們可以使用 configure(*options) 方法來更改列表框元件的屬性,例如背景顏色、前景色和其他屬性。width 屬性用於定義列表框元件的寬度。如果我們設定 width=0,那麼它將關閉為列表框中其內容的長度。

範例

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win=Tk()

# Set the size of the window
win.geometry("700x350")

# Add a Listbox widget with number as the list items
listbox =Listbox(win)
listbox.insert(END,"C++", "Java", "Python", "Rust", "GoLang", "Ruby", "JavaScript", "C# ", "SQL", "Dart")
listbox.pack(side=LEFT, fill=BOTH)

# Configure the Listbox widget to set the width to its content
listbox.configure(background="skyblue4", foreground="white", font=('Aerial 13'), width=0)

win.mainloop()

輸出

現在,執行上面的程式碼以顯示適應其內容的列表框。

更新於: 18-6 月-2021

2K+ 瀏覽量

開啟你的職業生涯

完成課程以獲得認證

立即開始
廣告