Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 40 ยท Widgets Basics

Tkinter Listbox and Scrollbar

Show and pick from lists with the Tkinter Listbox: insert and delete items, selection modes, curselection, virtual events, and connect a Scrollbar properly.

A Listbox shows a vertical list of text items and lets the user select one or several. Pair it with a Scrollbar when the list can be longer than the window. Together they are the classic way to build a file list, a todo list or a picker, and the connection between a listbox and a scrollbar is the template for scrolling every other widget.

Creating and filling a Listbox

Python
import tkinter as tk

root = tk.Tk()
fruits = tk.Listbox(root, height=6)
fruits.pack(padx=20, pady=20)

for name in ["Apple", "Banana", "Cherry", "Date", "Elderberry", "Fig", "Grape"]:
    fruits.insert(tk.END, name)

root.mainloop()
Method Meaning
insert(index, *items) Add one or more items before index (tk.END appends)
delete(first, last=None) Delete a range, inclusive on both ends for Listbox
get(first, last=None) Return one item, or a tuple for a range
size() Number of items
curselection() Tuple of selected indexes
selection_set(first, last=None), selection_clear(...) Change the selection
see(index) Scroll so the item is visible
activate(index) Move the keyboard cursor
itemconfig(index, bg=..., fg=...) Style one item

Note the difference from Entry and Text: Listbox.delete(0, tk.END) clears everything, and the range is inclusive at the end for a numbered index. listbox.get(0, tk.END) returns all items as a tuple.

You can fill a listbox in one step with the listvariable option and a StringVar holding a tuple or a space-separated string, which keeps it in sync with your data:

Python
items = tk.StringVar(value=("one", "two", "three"))
box = tk.Listbox(root, listvariable=items)
items.set(("alpha", "beta"))        # the listbox updates

Selection modes

selectmode decides how many items can be chosen:

Mode Behaviour
"browse" (default) One item; dragging moves the selection
"single" One item; click to select
"multiple" Click toggles items on and off
"extended" Click selects one; Ctrl-click adds; Shift-click selects a range

Most real programs want "extended" for multi-select and "browse" or "single" otherwise. Listboxes lose their selection when another widget takes focus (for example, an Entry) unless you set exportselection=False. If a form has two listboxes or a listbox and an entry, set it, or selections will seem to vanish.

Reacting to a selection

Listboxes have no command option. You bind the virtual event <<ListboxSelect>>, which fires whenever the selection changes:

Python
def on_select(event):
    indexes = box.curselection()
    if not indexes:                    # fires with an empty selection too
        return
    value = box.get(indexes[0])
    detail.config(text=f"You chose {value}")

box.bind("<<ListboxSelect>>", on_select)

Always handle the empty selection. The event also fires when focus changes and the selection is cleared, and curselection()[0] would raise IndexError.

A selection model you can run

The stand-in below implements the four selection modes with the same rules as Tk (single click, Ctrl-click, Shift-click), so you can predict what curselection() returns.

Python Stand-in: listbox selection modes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Adding the Scrollbar

A listbox shows only height lines. To scroll, connect the two widgets both ways:

  1. The listbox tells the scrollbar its position: yscrollcommand=scrollbar.set.
  2. The scrollbar tells the listbox to move: scrollbar.config(command=listbox.yview).
Python
import tkinter as tk

root = tk.Tk()
frame = tk.Frame(root)
frame.pack(fill="both", expand=True, padx=10, pady=10)

scrollbar = tk.Scrollbar(frame, orient="vertical")
listbox = tk.Listbox(frame, yscrollcommand=scrollbar.set, height=8, width=30)
scrollbar.config(command=listbox.yview)

scrollbar.pack(side="right", fill="y")
listbox.pack(side="left", fill="both", expand=True)

for i in range(1, 101):
    listbox.insert(tk.END, f"Item {i}")
root.mainloop()

The Scrollbar and the scrolled widget should share a parent Frame, which makes the pair behave as one unit and keeps the layout tidy. Pack the scrollbar first so it keeps its space when the window shrinks. For horizontal scrolling use orient="horizontal", xscrollcommand and xview.

The same recipe, yscrollcommand/yview, works for Text, Canvas, ttk.Treeview and Frame-in-Canvas scroll areas. The scrollbar's set(first, last) receives two fractions, the visible window as a share of the whole, and sizes the thumb. The maths is simple, and the stand-in shows it:

Python Stand-in: what a scrollbar is told

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A todo list in a few lines

Python
import tkinter as tk
from tkinter import messagebox

root = tk.Tk()
root.title("Todo")

entry = tk.Entry(root, width=28)
entry.grid(row=0, column=0, padx=6, pady=6)
todos = tk.Listbox(root, width=34, height=10, selectmode="extended")
todos.grid(row=1, column=0, columnspan=2, padx=6)

def add(event=None):
    text = entry.get().strip()
    if text:
        todos.insert(tk.END, text)
        entry.delete(0, tk.END)

def remove():
    selected = todos.curselection()
    if not selected:
        messagebox.showinfo("Todo", "Select an item first.")
        return
    for index in reversed(selected):         # delete from the end
        todos.delete(index)

entry.bind("<Return>", add)
tk.Button(root, text="Add", command=add).grid(row=0, column=1)
tk.Button(root, text="Remove selected", command=remove).grid(row=2, column=0, columnspan=2, pady=6)
root.mainloop()

Notice reversed(selected). Deleting an item shifts the indexes of everything below it, so deleting from the top would remove the wrong items. Always delete from the highest index down. The stand-in confirms the effect:

Python Stand-in: deleting several selected items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which event do you bind to react to a Listbox selection change?

    Listbox has no command option. The virtual event <<ListboxSelect>> fires when the selection changes.
  2. 2. Which selectmode allows Shift-click ranges and Ctrl-click additions?

    extended is the familiar file-manager style. multiple toggles items one at a time.
  3. 3. To scroll a Listbox, how must the Scrollbar and Listbox be connected?

    Each side informs the other: the widget reports its position, and the scrollbar requests moves.
  4. 4. Why delete selected listbox items from the highest index down?

    After deleting index 1, old index 3 becomes 2. Deleting from the end avoids stale indexes.

Summary

  • Listbox stores text items; use insert, delete, get, curselection and see.
  • selectmode is browse, single, multiple or extended; set exportselection=False when focus moves between widgets.
  • Bind <<ListboxSelect>> and handle the empty selection.
  • Connect a Scrollbar both ways: yscrollcommand=sb.set and sb.config(command=widget.yview).
  • Delete multiple selected items in reverse order.

Next: Scale and Spinbox