Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fit Tkinter listbox to contents

I'm adding strings to a listbox using the code below. When I run the code and the window opens, the longer strings get clipped as the window is not large enough (see screenshot). I have tried making the window resizeable and adding scroll bars but I was wondering if there was a way to automatically size it to fit the content.

master = tk.Tk()
listbox = tk.Listbox(master, selectmode=tk.SINGLE)

games = ["Garry's Mod", "Mount and Blade: Warband", "Tekkit"]
for game in sorted(games):
    listbox.insert(tk.END, game)

button = tk.Button(master, text="Execute", command=execute)

listbox.pack()
button.pack()
tk.mainloop()

example of clipped listbox

like image 954
ftm Avatar asked Mar 29 '13 14:03

ftm


People also ask

How do I resize a Listbox in Python?

Practical Data Science using Python We can configure the Listbox widget property by using expand=True and fill=BOTH property. These properties ensure that the widget stretches both vertically and horizontally. However, expand allows the widget to grow in available space.

How do I add data to a Listbox in Python?

A listbox shows a list of options. You can then click on any of those options. By default it won't do anything, but you can link that to a callback function or link a button click. To add new items, you can use the insert() method.

What is the default selection mode of a Listbox widget?

The default is SUNKEN. The background color to use displaying selected text. BROWSE − Normally, you can only select one line out of a listbox. If you click on an item and then drag to a different line, the selection will follow the mouse.

What is the use of Listbox widget?

The Listbox widget is used to display the list items to the user. We can place only text items in the Listbox and all text items contain the same font and color. The user can choose one or more items from the list depending upon the configuration. The syntax to use the Listbox is given below.


1 Answers

Resetting the listbox width worked for me. I used the Oblivion's answer and noticed that the width is always zero.

listbox = tk.Listbox(master, selectmode=tk.SINGLE)
listbox.config(width=0)

I also recommend to reset the root window geometry after reloading a content of the list. Otherwise if user manually extends a window the window would stop accommodate size of its content.

root.winfo_toplevel().wm_geometry("")
like image 153
frantisek Avatar answered Sep 20 '22 11:09

frantisek