How to fit Tkinter listbox to contents?

TkinterPythonGUI-Programming

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.

Example

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

Output

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

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