How to fit Tkinter listbox to contents?


Tkinter offers Listbox widgets which is very useful in the case of representing a large set of data items in the form of a list. To configure the listbox widget, we can use configure(*options) method to change the properties such as background color, foreground color, and other properties of the listbox widget. The width property is used to define the width of the listbox widget. If we set width=0, then it will get closed to the length of its content in the listbox.


# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window

# Set the size of the window

# 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)



Now, run the above code to display the listbox which is set to its content.

Published on 18-Jun-2021 14:23:05