如何调整 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+ 浏览量

开启你的职业生涯

完成课程以获得认证

立即开始
广告
© . All rights reserved.