Tkinter Listbox: insert(), curselection() and Multiple Selection

The Tkinter Listbox widget displays a vertical list of single-line items. Depending on its selectmode, the user can select one item or several items.

Python Tkinter Listbox widget with selectable options


Tkinter Listbox Widget for User Selection

Create a Tkinter Listbox 🔝

import tkinter as tk

root=tk.Tk()
root.geometry('400x250')
root.title('Tkinter Listbox - plus2net')

font1=('Arial', 15)

lb1=tk.Listbox(root, height=6, font=font1, bg='lightgreen')
lb1.grid(row=0, column=0, padx=30, pady=20)

lb1.insert(tk.END, 'PHP')
lb1.insert(tk.END, 'MySQL')
lb1.insert(tk.END, 'Python')
lb1.insert(tk.END, 'JavaScript')

root.mainloop()

Each item appears on a separate line. The Listbox itself does not provide a drop-down button; the choices remain visible inside the widget.

Add Items with insert() 🔝

The syntax is:

listbox.insert(index, item1, item2, ...)

Append an Item

lb1.insert(tk.END, 'Python')

Insert at the Beginning

lb1.insert(0, 'HTML')

Insert Several Items

lb1.insert(tk.END, 'PHP', 'Python', 'MySQL')

Add Items from a Python List

languages=['PHP', 'Python', 'MySQL']

for language in languages:
    lb1.insert(tk.END, language)

Listbox Indexes Start at 0 🔝

The first Listbox item has index 0.

lb1.insert(tk.END, 'PHP')
lb1.insert(tk.END, 'Python')
lb1.insert(tk.END, 'MySQL')

print(lb1.get(0))
print(lb1.get(2))
Sample Output
PHP
MySQL

For insert(), tk.END represents the position after the final item, so it is the clearest way to append new data.

Read Listbox Items with get() 🔝

Read One Item

value=lb1.get(1)
print(value)

Read a Range

values=lb1.get(0, tk.END)
print(values)
Sample Output
('PHP', 'Python', 'MySQL')

When a range is requested, get() returns the items as a tuple.

Read the Selected Item with curselection() 🔝

curselection() returns a tuple containing the indexes of all currently selected items.

selected=lb1.curselection()
print(selected)

With one selected item:

(1,)

If nothing is selected:

()

Get the Selected Value

selected=lb1.curselection()

if selected:
    index=selected[0]
    value=lb1.get(index)
    print(index, value)

Read Selection on Button Click

import tkinter as tk

def show_selected():
    selected=lb1.curselection()

    if selected:
        print(lb1.get(selected[0]))
    else:
        print('No item selected')

root=tk.Tk()

lb1=tk.Listbox(root, height=4)
lb1.pack(padx=20, pady=10)

for item in ('PHP', 'Python', 'MySQL'):
    lb1.insert(tk.END, item)

tk.Button(root, text='Show Selected', command=show_selected).pack(pady=10)

root.mainloop()

Use <<ListboxSelect>> Event 🔝

The virtual event <<ListboxSelect>> is generated when the Listbox selection changes.

import tkinter as tk

def selection_changed(event):
    selected=event.widget.curselection()

    if not selected:
        return

    index=selected[0]
    value=event.widget.get(index)
    print('Selected:', index, value)

root=tk.Tk()

lb1=tk.Listbox(root)
lb1.pack(padx=20, pady=20)

for item in ('PHP', 'Python', 'MySQL'):
    lb1.insert(tk.END, item)

lb1.bind('<<ListboxSelect>>', selection_changed)

root.mainloop()

Using event.widget makes the callback reusable with different Listbox widgets.

Selected Item vs ACTIVE vs ANCHOR 🔝

These concepts are related but are not interchangeable.

Value / MethodMeaning
curselection()Indexes of items currently selected by the user or application.
tk.ACTIVEThe active/location-cursor item.
tk.ANCHORThe selection anchor used when extending a selection.

Read the Active Item

print(lb1.get(tk.ACTIVE))

This reads the active item, but it should not be used as a replacement for curselection() when the application needs the user's selected value.

Activate an Item

lb1.activate(2)

Display the Selected Item in a Label 🔝

Display Tkinter Listbox Selection in a Label

Displaying selected Tkinter Listbox item in Label

A StringVar can be connected to a Label and updated whenever the Listbox selection changes.

import tkinter as tk

def selection_changed(event):
    selected=lb1.curselection()

    if selected:
        output_var.set(lb1.get(selected[0]))
    else:
        output_var.set('')

root=tk.Tk()
root.geometry('450x250')

lb1=tk.Listbox(root, height=6, font=('Arial', 15), bg='lightgreen')
lb1.grid(row=0, column=0, padx=30, pady=20)

for item in ('PHP', 'Python', 'MySQL', 'HTML', 'jQuery'):
    lb1.insert(tk.END, item)

output_var=tk.StringVar()
label=tk.Label(root, textvariable=output_var, bg='lightyellow', font=('Arial', 15))
label.grid(row=0, column=1, padx=5)

lb1.bind('<<ListboxSelect>>', selection_changed)

root.mainloop()

Select Multiple Listbox Items 🔝

Multiple Selection with Tkinter Listbox

Multiple selection using Tkinter Listbox selectmode

Set selectmode to multiple or extended when several items may be selected.

lb1=tk.Listbox(root, selectmode=tk.MULTIPLE)

curselection() can then contain several indexes.

def show_selected(event=None):
    selected=lb1.curselection()
    values=[lb1.get(index) for index in selected]
    output_var.set(', '.join(values))

Complete Multiple Selection Example

import tkinter as tk

def selection_changed(event):
    selected=lb1.curselection()
    values=[lb1.get(index) for index in selected]
    output_var.set(', '.join(values))

root=tk.Tk()

lb1=tk.Listbox(root, height=6, selectmode=tk.MULTIPLE, exportselection=False)
lb1.grid(row=0, column=0, padx=10, pady=20)

for item in ('PHP', 'Python', 'MySQL', 'HTML', 'jQuery'):
    lb1.insert(tk.END, item)

output_var=tk.StringVar()
tk.Label(root, textvariable=output_var, bg='lightyellow', width=30).grid(row=0, column=1, padx=10)

lb1.bind('<<ListboxSelect>>', selection_changed)

root.mainloop()

The list comprehension:

values=[lb1.get(index) for index in selected]

creates a Python list containing all selected values.

Listbox selectmode Options 🔝

ModeSelection Behaviour
tk.SINGLEAt most one item is selected.
tk.BROWSEAt most one item is selected; this is the normal default browsing behaviour.
tk.MULTIPLESeveral items can be toggled independently.
tk.EXTENDEDSupports multiple selection including ranges using normal desktop selection behaviour.

Single Selection

lb1=tk.Listbox(root, selectmode=tk.SINGLE)

Browse Selection

lb1=tk.Listbox(root, selectmode=tk.BROWSE)

Multiple Selection

lb1=tk.Listbox(root, selectmode=tk.MULTIPLE)

Extended Selection

lb1=tk.Listbox(root, selectmode=tk.EXTENDED)
Choosing between MULTIPLE and EXTENDED: MULTIPLE is useful when each item should be toggled independently. EXTENDED behaves more like a desktop file-selection list, where ranges and modifier-key selections are useful.

Select Listbox Items with Python 🔝

Select One Item

lb1.selection_set(1)

Select a Range

lb1.selection_set(1, 3)

Clear One Selection

lb1.selection_clear(1)

Clear All Selections

lb1.selection_clear(0, tk.END)

Check whether an Item Is Selected

print(lb1.selection_includes(2))

Make an Item Visible

lb1.see(10)

Delete Items from a Listbox 🔝

Delete by Index

lb1.delete(2)

This deletes the item at index 2, which is the third item.

Delete All Items

lb1.delete(0, tk.END)

Delete the Selected Item

def delete_selected():
    selected=lb1.curselection()

    if selected:
        lb1.delete(selected[0])

This is safer than assuming that tk.ANCHOR represents the selected item.

Delete Multiple Selected Items

Delete indexes from highest to lowest so earlier deletions do not shift the remaining indexes.

def delete_selected():
    selected=lb1.curselection()

    for index in reversed(selected):
        lb1.delete(index)

Read All Listbox Items 🔝

The simplest way to read all current Listbox values is:

items=lb1.get(0, tk.END)
print(items)
Sample Output
('PHP', 'Python', 'MySQL')

Number of Items

Use size():

print(lb1.size())
Sample Output
3

Get the Last Item

if lb1.size() > 0:
    print(lb1.get(tk.END))

Populate Listbox with listvariable 🔝

The listvariable option connects the Listbox contents to a Tkinter variable containing a Tcl list.

import tkinter as tk

root=tk.Tk()

items=('PHP', 'Python', 'MySQL')
items_var=tk.Variable(value=items)

lb1=tk.Listbox(root, listvariable=items_var)
lb1.pack(padx=20, pady=20)

print(items_var.get())

root.mainloop()
Sample Output
('PHP', 'Python', 'MySQL')

For simply reading the current Listbox contents, this is often clearer:

items=lb1.get(0, tk.END)

Add a Scrollbar to Listbox 🔝

A Listbox inherits scrolling behaviour, so it can be connected to a vertical Scrollbar.

import tkinter as tk
from tkinter import ttk

root=tk.Tk()

frame=tk.Frame(root)
frame.pack(padx=20, pady=20)

scrollbar=ttk.Scrollbar(frame, orient='vertical')
scrollbar.pack(side='right', fill='y')

lb1=tk.Listbox(frame, height=8, yscrollcommand=scrollbar.set)
lb1.pack(side='left')

scrollbar.config(command=lb1.yview)

for number in range(1, 31):
    lb1.insert(tk.END, f'Item {number}')

root.mainloop()
Tkinter Scrollbar Examples

Important Tkinter Listbox Options 🔝

OptionPurpose
bg / backgroundBackground color.
fg / foregroundText color.
fontFont family, size and style.
heightRequested number of visible rows.
widthRequested width in characters.
selectmodeControls single or multiple selection behaviour.
selectbackgroundBackground color of selected items.
selectforegroundText color of selected items.
statenormal or disabled.
listvariableVariable containing the Listbox items.
exportselectionControls whether the widget exports its selection to the window-system selection.
activestyleAppearance of the active item.
cursorMouse cursor shown over the widget.
reliefBorder appearance.
bd / borderwidthBorder width.
highlightcolorFocus-highlight color.
highlightbackgroundHighlight color when the widget does not have focus.
highlightthicknessWidth of the focus-highlight border.
xscrollcommandConnects a horizontal scrollbar.
yscrollcommandConnects a vertical scrollbar.

Background and Foreground

lb1=tk.Listbox(root, bg='yellow', fg='green')

Font

my_font=('Times', 12, 'underline')
lb1=tk.Listbox(root, font=my_font)

Selection Colors

lb1=tk.Listbox(root, selectbackground='yellow', selectforeground='green')

Disable the Listbox

lb1.config(state='disabled')

Enable it again:

lb1.config(state='normal')

Focus Highlight

Tkinter Listbox focus highlight options

lb1=tk.Listbox(root, highlightcolor='yellow', highlightthickness=5)

Relief

Tkinter Listbox relief border styles

Common relief values are:

'raised'
'sunken'
'flat'
'ridge'
'solid'
'groove'

Example:

lb1=tk.Listbox(root, height=3, relief='ridge')

exportselection=False

This option is especially useful when an interface contains more than one Listbox and each widget should retain its visible selection independently.

lb1=tk.Listbox(root, exportselection=False)

Listbox vs Combobox vs OptionMenu 🔝

These widgets all present choices, but they suit different interfaces.

WidgetBest UseMultiple Selection
ListboxSeveral choices should remain visible at the same time.Yes
ttk.ComboboxCompact drop-down selection, optionally with editable text.No
OptionMenuSimple single-selection drop-down from a predefined set.No

Choose Listbox When

  • users should see several available options without opening a menu,
  • multiple selection is required,
  • the list will be scrolled,
  • selection changes should immediately update another part of the interface.

Choose Combobox When

The application needs a compact field with a drop-down list, especially when the available screen space is limited.

Tkinter Combobox Tutorial

Listbox Options from a Database 🔝

Listbox choices do not have to be hard-coded. They can also come from a database or another external data source.

Populate Listbox from Database Table

Autocomplete with Entry and Listbox 🔝

A Listbox can display suggestions while the user types into an Entry field.

Tkinter Autocomplete using Entry and Listbox

Exercises on Tkinter Listbox 🔝

  1. Add items entered by the user to a Listbox.
  2. Create one Button to delete all Listbox items and another Button to delete the currently selected item.
  3. Create a Listbox with ten items. Add a Button that always deletes the item at index 2. Observe what happens when the Button is clicked repeatedly.
  4. Create three columns:
    • a Listbox containing PHP, MySQL and Python,
    • three Checkbuttons containing the same options,
    • three Radiobuttons containing the same options.
    When an item is selected in the Listbox, update the matching Checkbutton and Radiobutton.
  5. Use the CSV file from the dictionary tutorial. Populate a Listbox with student names. When a student is selected, display the corresponding subject marks and attendance, then calculate the total marks and attendance.
Tkinter student Listbox project using CSV data

Listbox Exercise Solutions

Summary of Tkinter Listbox 🔝

  • Listbox displays single-line choices in a visible list.
  • Listbox item indexes start at 0.
  • Use insert(tk.END, value) to append items.
  • insert(index, ...) inserts items before the specified index.
  • Use get(index) to read one item.
  • Use get(0, tk.END) to read all items.
  • Use size() to get the number of items.
  • curselection() returns a tuple of selected indexes.
  • Always check whether curselection() is empty before accessing an index.
  • Use <<ListboxSelect>> to react to selection changes.
  • tk.ACTIVE represents the active item, not necessarily the selected item.
  • tk.ANCHOR represents the selection anchor.
  • Use selection_set() to select items programmatically.
  • Use selection_clear() to deselect items.
  • selectmode supports single, browse, multiple and extended.
  • Use multiple or extended when several items may be selected.
  • When deleting multiple selected items, delete indexes in reverse order.
  • listvariable can provide Listbox contents through a Tkinter variable.
  • Listbox supports horizontal and vertical scrolling.
  • Use exportselection=False when selections should remain independent across multiple selection widgets.
  • Use Listbox when choices should remain visible or multiple selection is required.
  • Use Combobox or OptionMenu when a compact single-selection control is more suitable.
Listbox with Scrollbar Listbox from Database Autocomplete Combobox OptionMenu




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer