What is ListBox?

The ListBox widget is used to create a list of options or items, it is a standard Tkinter widget. ListBox can only contain text items, however, you can change the color and font values for items. 

The ListBox widget is useful when you want to show a list of some items, from where the user can select only or multiple items.

Example

The following python script creates a ListBox with five items, You need to write following code in any text editor and then save it with .py extension. To execute the application type python ListBoxExample.py command in terminal. 

from tkinter import *

# Top level window 
window = Tk()

window.title("Studyfied.com")
window.geometry('350x200')

# Create listbox
listbox = Listbox(window, activestyle = NONE)
listbox.pack()

# Insert five items at end of the list
listbox.insert(END, "Item 1")
listbox.insert(END, "Item 2")
listbox.insert(END, "Item 3")
listbox.insert(END, "Item 4")

# Insert at index 0.
listbox.insert(0, "Item 0")

window.mainloop()

Output

The above code produces the following output in windows operating system.

Explanation

Following line creates a Tkinter window

from tkinter import *

window = Tk()

window.title("Studyfied.com")
window.geometry('350x200')

See explanation of Tkinter window – Tkinter top level window


This two lines creates ListBox, The first parameter of the ListBox is the name of the parent window or widget. Here it is “window”. The second parameter is activestyle with value NONE. activestyle is optional parameter by default underline is used as activestyle, And the second line listbox.pack() is geometry manager that packs widgets into rows or columns. 

# Create listbox
listbox = Listbox(window, activestyle = NONE)
listbox.pack()

This snippet inserts five items to the list box, We can insert N number of items by calling insert() method, the first parameter of this method is index or position of an item and the second one is value. 

# Insert four items at end of the list
listbox.insert(END, "Item 1")
listbox.insert(END, "Item 2")
listbox.insert(END, "Item 3")
listbox.insert(END, "Item 4")

# Insert at index 0.
listbox.insert(0, "Item 0")

Some ListBox properties

Property NameDescription
background / bgSets the background color for this widget. The default is ‘SystemButtonFace’.
borderwidth / bdBorder width for this widget. The default is system specific but usually 1 to 2 pixels.
cursorThe cursor to display when the mouse moves over the widget. By default, the standard cursor is used.
foreground / fgSets the color for label text. Default is system specified
fontFont to use for items. Default is system specified.
heightSets the listbox height in pixels. Default value is 10.
selectbackgroundSets the selected item background color. Default is system specific
selectborderwidthSets the width for selected item. Default is 1
selectforegroundSets the foreground color selected item. Default is system specific
widthWidth for listbox. Default is 20