ZetCode

Tk listbox and treeview

last modified November 24, 2026 Tcl 8.6

Lists of choices and tables of records are the backbone of many desktop tools. Tk offers two widgets for them. The classic listbox shows a flat, single-column list and is enough for a colour chooser or a queue. The themed ttk::treeview shows rows with several columns and, when needed, a tree of nested items.

This article builds both widgets step by step, from an empty list to a scrolling table and a small record viewer with a detail panel. The examples print the widget state with puts, so they can be run without a display.

The listbox widget

A listbox stores a list of strings and shows as many rows as its height allows. Items are addressed by a zero-based index, and end refers to the last item. The first script fills a listbox with a loop and reads its contents back.

listbox_intro.tcl
package require Tk

listbox .lb -height 6 -width 20
pack .lb -padx 8 -pady 8

foreach item {coffee bread milk tea} {
    .lb insert end $item
}
update
puts "size:  [.lb size]"
puts "first: [.lb get 0]"
puts "all:   [.lb get 0 end]"

.lb delete 1
update
puts "after delete: [.lb get 0 end]"

destroy .

insert end appends one item, and get 0 end returns the whole list as a Tcl list, so it can be passed to foreach or llength directly. Deleting index 1 removed bread and moved the remaining rows up. The Tcl list command page covers the list operations that work on these values.

$ wish listbox_intro.tcl
size:  4
first: coffee
all:   coffee bread milk tea
after delete: coffee milk tea

Inserting and selecting items

Selection is separate from the item text. A listbox can allow one item or many, and the application reads the selected indices with curselection. The next script allows extended selection and marks two rows programmatically, the same way a user would with the mouse.

listbox_select.tcl
package require Tk

listbox .lb -height 6 -width 20 -selectmode extended -exportselection 0
pack .lb -padx 8 -pady 8

foreach item {coffee bread milk tea juice} {
    .lb insert end $item
}

.lb selection set 1
.lb selection set 3
.lb activate 1
update
puts "selected:  [.lb curselection]"
puts "items:     [.lb get 1] [.lb get 3]"
puts "is 2 in:   [.lb selection includes 2]"
puts "active:    [.lb index active]"

.lb selection clear 1
update
puts "after clear: [.lb curselection]"

destroy .

curselection returned the indices 1 3, not the item texts, so the application usually maps them with get. The -exportselection 0 option keeps the selection visible when another widget takes ownership of the X selection. The active item is the row that keyboard actions start from; it is set with activate and read with index active.

$ wish listbox_select.tcl
selected:  1 3
items:     bread tea
is 2 in:   0
active:    1
after clear: 3

The ttk::treeview widget

ttk::treeview is part of the themed widget set: its headings, scrollbars and rows follow the current ttk theme instead of the classic Tk look. The widget holds a tree of items identified by strings, so each row can have children. This script creates two branches and reads their labels.

treeview_intro.tcl
package require Tk

ttk::treeview .tree -height 5
pack .tree -padx 8 -pady 8

.tree insert {} end -id fruit -text "Fruit"
.tree insert fruit end -text "Apple"
.tree insert fruit end -text "Pear"
.tree insert {} end -id veg -text "Vegetables"
.tree insert veg end -text "Carrot"

update
puts "top level: [.tree children {}]"
puts "fruit:     [.tree children fruit]"
puts "label:     [.tree item fruit -text]"
puts "veg label: [.tree item veg -text]"

.tree item fruit -open 1
puts "open now:  [.tree item fruit -open]"

.tree delete veg
puts "after delete: [.tree children {}]"

destroy .

The parent {} in insert means the root of the tree. Explicit -id values make the items easy to address later, while children without an id get generated names such as I001. children lists the direct children of an item, item -text reads a label and item -open expands or collapses a branch. Deleting an item also deletes its subtree.

$ wish treeview_intro.tcl
top level: fruit veg
fruit:     I001 I002
label:     Fruit
veg label: Vegetables
open now:  1
after delete: fruit

Columns and headings

For tabular data the treeview switches to columns. The -columns option names the data columns, -show headings hides the tree column and shows a heading row, and each heading and column is configured separately. The next script sets titles, widths and alignment.

columns.tcl
package require Tk

ttk::treeview .stock -columns {item qty} -show headings -height 4
pack .stock -padx 8 -pady 8

.stock heading item -text "Item"
.stock heading qty -text "Quantity"
.stock column item -width 160 -anchor w
.stock column qty -width 80 -anchor e

update
puts "columns: [.stock cget -columns]"
puts "shown:   [.stock cget -show]"
puts "heading: [.stock heading item -text]"
puts "width:   [.stock column item -width]"

.stock heading qty -text "In stock"
puts "renamed: [.stock heading qty -text]"

destroy .

Column names item and qty are internal identifiers; the visible titles are set with heading -text and can be changed at run time. column -anchor e right-aligns the numbers, which is the usual choice for quantities. Without -show headings the first column would be the tree column and the data columns would have no titles.

$ wish columns.tcl
columns: item qty
shown:   headings
heading: Item
width:   160
renamed: In stock

Inserting rows

A data row is inserted with a list of values, one per column, and the insert subcommand returns the item id. The application can ignore the id, but keeping it makes later updates cheap. Values are read back with item -values or a single cell with set.

insert_rows.tcl
package require Tk

ttk::treeview .stock -columns {item qty} -show headings -height 5
pack .stock -padx 8 -pady 8
.stock heading item -text "Item"
.stock heading qty -text "Qty"

foreach {name count} {coffee 3 bread 7 milk 2 tea 5} {
    set id [.stock insert {} end -values [list $name $count]]
    puts "inserted $id: $name, $count"
}
update

puts "rows:  [.stock children {}]"
puts "first: [.stock item I001 -values]"
puts "cell:  [.stock set I001 item]"

.stock item I002 -tags {low}
puts "tags:  [.stock item I002 -tags]"

.stock delete I004
puts "after delete: [.stock children {}]"

destroy .

The foreach loop walks the flat list two elements at a time, which is a common way to feed a table from a literal list or a file. Each row got a generated id in sequence. Tags attach names to rows for styling, and rows can be removed by id without touching the others. The Tcl foreach command page explains the two-variable form used in the loop.

$ wish insert_rows.tcl
inserted I001: coffee, 3
inserted I002: bread, 7
inserted I003: milk, 2
inserted I004: tea, 5
rows:  I001 I002 I003 I004
first: coffee 3
cell:  coffee
tags:  low
after delete: I001 I002 I003

Selection and item values

Selection works with item ids. selection set selects a row, selection returns the selected ids, focus names the row with the focus rectangle and see scrolls a row into view. Changing one cell is a single command.

selection_values.tcl
package require Tk

ttk::treeview .stock -columns {item qty} -show headings -height 5
pack .stock -padx 8 -pady 8
.stock heading item -text "Item"
.stock heading qty -text "Qty"

foreach {name count} {coffee 3 bread 7 milk 2} {
    .stock insert {} end -values [list $name $count]
}
update

.stock selection set I002
.stock focus I002
.stock see I002
puts "selection: [.stock selection]"
puts "focus:     [.stock focus]"
puts "values:    [.stock item I002 -values]"

.stock set I002 qty 9
puts "updated:   [.stock item I002 -values]"

.stock selection remove I002
puts "left:      '[.stock selection]'"

destroy .

set takes the item id, the column name and the new value, so a quantity can be edited without rebuilding the row. The selection is a list even when the widget is configured for single selection, which keeps the code ready for extended mode. see had nothing to do in this short table, but in a long one it is what makes selection set visible to the user.

$ wish selection_values.tcl
selection: I002
focus:     I002
values:    bread 7
updated:   bread 9
left:      ''

A table with scrolling

A table of forty rows does not fit in a six-row widget, so it needs a scrollbar. The treeview and the scrollbar are connected through -yscrollcommand and -command, exactly like the text widget from the previous article.

table_scroll.tcl
package require Tk

ttk::treeview .table -columns {n square} -show headings -height 6 \
    -yscrollcommand {.sb set}
scrollbar .sb -orient vertical -command {.table yview}
grid .table -row 0 -column 0 -sticky nsew
grid .sb -row 0 -column 1 -sticky ns
.table heading n -text "Number"
.table heading square -text "Square"
.table column n -width 90 -anchor e
.table column square -width 90 -anchor e

for {set i 1} {$i <= 40} {incr i} {
    .table insert {} end -values [list $i [expr {$i * $i}]]
}
update
set range [.table yview]
puts "yview:      [format {%.2f %.2f} [lindex $range 0] [lindex $range 1]]"
puts "row at 20:  [.table identify row 20 20]"

.table yview moveto 1.0
update
set range [.table yview]
set last [lindex [.table children {}] end]
puts "after moveto 1.0:"
puts "yview:      [format {%.2f %.2f} [lindex $range 0] [lindex $range 1]]"
puts "last row:   [.table item $last -values]"
puts "row at 20:  [.table identify row 20 20]"

destroy .

yview returns the visible fraction of the table, from 0.00 to 0.15 at the top. identify row converts widget coordinates into an item id, which is how a context menu or a tooltip finds the row under the pointer. After scrolling to the bottom, the same coordinates point at a different row and the last item holds 1600, the square of 40.

$ wish table_scroll.tcl
yview:      0.00 0.15
row at 20:  I001
after moveto 1.0:
yview:      0.85 1.00
last row:   40 1600
row at 20:  I022

A small record viewer

The last example puts the pieces together: a treeview of records and a detail label below it. The label is updated from a <<TreeviewSelect>> binding, which Tk fires whenever the user changes the selection. A script can trigger the same binding with event generate.

record_viewer.tcl
package require Tk

set details "Select a record"

proc show_record {} {
    global details
    set sel [.records selection]
    if {$sel eq ""} {
        set details "Select a record"
        return
    }
    set values [.records item $sel -values]
    set details "ID [lindex $values 0]: [lindex $values 1], [lindex $values 2]"
}

ttk::treeview .records -columns {id name city} -show headings -height 6
.records heading id -text "ID"
.records heading name -text "Name"
.records heading city -text "City"
.records column id -width 50 -anchor center
.records column name -width 120
.records column city -width 130

label .details -textvariable details -anchor w -relief sunken
pack .records -padx 8 -pady 6 -fill both -expand 1
pack .details -fill x -padx 8 -pady 6

foreach record {{1 Jane Bratislava} {2 Peter Kosice} {3 Eva Zilina}} {
    .records insert {} end -values $record
}
bind .records <<TreeviewSelect>> show_record

.records selection set I002
event generate .records <<TreeviewSelect>>
update
puts "first:  $details"

.records selection set I003
event generate .records <<TreeviewSelect>>
update
puts "second: $details"

.records selection remove I003
update
puts "cleared: '[.records selection]'"

destroy .

show_record guards against an empty selection, then splits the row values with lindex and writes the detail text into a variable, which the label displays. Programmatic selection set does not fire the virtual event, so the test generates it explicitly. A real click can fire it more than once, which is harmless because the procedure only reads the current selection. Reading the values from the widget keeps the procedure independent of how the table was filled.

$ wish record_viewer.tcl
first:  ID 2: Peter, Kosice
second: ID 3: Eva, Zilina
cleared: ''

Source

The listbox and treeview manual pages document the item indices, column and heading options, tags and virtual events used here. The ttk manual covers the themed widget set as a whole.

This article covered flat lists in the listbox, hierarchical items and tabular rows in the treeview, selection handling, item updates and scrolling. Continue with Tk ttk widgets and themes for the rest of the themed widget set, or read the Tcl lindex command page for the list indexing used in the record viewer.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Tcl Tutorials.