ZetCode

Tk application structure

last modified November 24, 2026 Tcl 8.6

A Tk program usually begins as one window with a few widgets and then grows: menus appear, a toolbar follows, dialogs open, and the window size has to be remembered between runs. This article builds that structure around a small notes application. Each section adds one part and produces a script that runs on its own.

The examples use Tk 8.6 and only widgets that ship with it. Every script closes its window with a timer, so it can run unattended; a real program leaves the window open and lets wish process events. The timer and event loop behaviour is described on the Tcl after command page.

A single-window application skeleton

The main window is the widget named . (a dot). Every other widget is created below it, so a button in a toolbar has a path such as .toolbar.open. The path is also the command used to configure the widget later, which is why Tk code reads like a series of dotted names.

app_skeleton.tcl
# app_skeleton.tcl - one window, a few widgets, no menus yet
wm title . "Notes"
wm geometry . 420x260

label .title -text "Notes" -font {Helvetica 16 bold}
label .hint -text "A single-window application skeleton."
button .quit -text "Quit" -command exit

pack .title -side top -pady {18 6}
pack .hint -side top
pack .quit -side bottom -pady 14

after 800 {
    puts "window ready: [winfo width .]x[winfo height .]"
    destroy .
}

wm title and wm geometry talk to the window manager, not to a widget. The three widgets are packed from the top and the bottom, and pack gives the window its requested size. The timer at the end prints the actual size and destroys the window; destroy . is what lets this example finish. In a real program the timer is left out: once the script has been read, wish keeps processing events, so the window stays open until the user closes it.

$ wish app_skeleton.tcl
window ready: 420x260

A menu and toolbar

Menus hold commands that apply to the whole application, such as opening a file or quitting. A toolbar repeats the two or three commands used most often, so they are one click away. Both are ordinary Tk widgets: a menu is a widget tree of its own, attached to the main window with a single option.

app_menu.tcl
# app_menu.tcl - a menu bar and a toolbar above the content area
wm title . "Notes"
wm geometry . 480x300

menu .menubar -tearoff 0
menu .menubar.file -tearoff 0
menu .menubar.view -tearoff 0
menu .menubar.help -tearoff 0

.menubar.file add command -label "New note" -accelerator "Ctrl+N" \
    -command {puts "new note"}
.menubar.file add separator
.menubar.file add command -label "Quit" -command exit

.menubar.view add command -label "Status bar" -command {puts "toggle status"}
.menubar.help add command -label "About Notes" -command {puts "about"}

.menubar add cascade -label File -menu .menubar.file
.menubar add cascade -label View -menu .menubar.view
.menubar add cascade -label Help -menu .menubar.help
. configure -menu .menubar

frame .toolbar -background "#e8e8e8"
ttk::button .toolbar.new -text "New" -command {puts "new note"}
ttk::button .toolbar.about -text "About" -command {puts "about"}
pack .toolbar.new .toolbar.about -side left -padx 4 -pady 4
pack .toolbar -side top -fill x

label .body -text "The content area will hold the note list." \
    -foreground "#444444"
pack .body -expand 1

after 800 {
    puts "top-level menus: [expr {[.menubar index end] + 1}]"
    puts "first File item: [.menubar.file entrycget 0 -label]"
    destroy .
}

menu .menubar creates the bar, and each submenu is a child of it. The -tearoff 0 option removes the dashed tear-off entry that Tk adds by default. Inside a menu, add cascade attaches a submenu, add command adds an item and add separator draws a line. The -accelerator text is only a hint for the user; the key binding itself has to be created with bind. The toolbar uses ttk::button, which follows the native look of the platform.

$ wish app_menu.tcl
top-level menus: 3
first File item: New note

A status bar

A status bar reports what the application just did and where the user is. It is a label pinned to the bottom of the window, packed before the part of the window that expands, so resizing never hides it. A small procedure keeps all messages in one place instead of repeating a long configure call.

app_status.tcl
# app_status.tcl - a status bar that reports what the application is doing
wm title . "Notes"
wm geometry . 480x320

proc set_status {text} {
    .status configure -text $text
}

menu .menubar -tearoff 0
menu .menubar.file -tearoff 0
menu .menubar.help -tearoff 0

.menubar.file add command -label "New note" -command {
    .body delete 1.0 end
    set_status "New note"
}
.menubar.file add command -label "Count words" -command {
    set words [llength [split [.body get 1.0 end]]]
    set_status "$words words"
}
.menubar.file add separator
.menubar.file add command -label "Quit" -command exit
.menubar.help add command -label "About Notes" -command {
    set_status "Notes 1.0"
}
.menubar add cascade -label File -menu .menubar.file
.menubar add cascade -label Help -menu .menubar.help
. configure -menu .menubar

label .status -text "Ready" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x

text .body -wrap word -undo 1
.body insert end "First note\nSecond note\n"
pack .body -expand 1 -fill both

after 600 {
    puts "status: [.status cget -text]"
    set_status "Two notes loaded"
    puts "status: [.status cget -text]"
    destroy .
}

The status label uses -anchor w so its text starts at the left edge, and -relief sunken gives it the familiar recessed look. set_status receives one string and updates the label; every menu command calls it. The word count is a realistic example: it reports a result without opening a dialog or changing the document. Packing the status bar before the text widget is what keeps it at the bottom when the window grows.

$ wish app_status.tcl
status: Ready
status: Two notes loaded

A second window with toplevel

Not every view belongs in the main window. The toplevel command creates an independent window that shares the interpreter, fonts and images with the application. A document can therefore be opened in its own window while the main window stays visible behind it.

app_window.tcl
# app_window.tcl - a second window built with toplevel
wm title . "Notes"
wm geometry . 480x320

proc set_status {text} {
    .status configure -text $text
}

proc open_note {} {
    toplevel .note_win
    wm title .note_win "Note"
    wm transient .note_win .
    wm geometry .note_win 340x220
    wm protocol .note_win WM_DELETE_WINDOW {destroy .note_win}

    text .note_win.body -wrap word -undo 1
    .note_win.body insert end "Groceries\nCall the plumber\n"
    button .note_win.close -text "Close" \
        -command {destroy .note_win}
    pack .note_win.body -expand 1 -fill both
    pack .note_win.close -side bottom -pady 6
    set_status "Note window opened"
}

menu .menubar -tearoff 0
menu .menubar.file -tearoff 0
menu .menubar.help -tearoff 0

.menubar.file add command -label "New note" -command {
    .body delete 1.0 end
    set_status "New note"
}
.menubar.file add command -label "Open in window" -command open_note
.menubar.file add separator
.menubar.file add command -label "Quit" -command exit
.menubar.help add command -label "About Notes" -command {
    set_status "Notes 1.0"
}
.menubar add cascade -label File -menu .menubar.file
.menubar add cascade -label Help -menu .menubar.help
. configure -menu .menubar

label .status -text "Ready" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x

text .body -wrap word -undo 1
.body insert end "First note\nSecond note\n"
pack .body -expand 1 -fill both

after 500 {
    open_note
    after 400 {
        puts "second window exists: [winfo exists .note_win]"
        puts "status: [.status cget -text]"
        puts "parent: [wm transient .note_win]"
        destroy .
    }
}

All widgets of the second window live under .note_win, so their paths stay unique and the whole window can be destroyed with one command. wm transient tells the window manager that this window belongs to the main one, which usually keeps it above its parent. The WM_DELETE_WINDOW handler is registered for the new window as well, because its Close button and its title-bar button must run the same code. grab, which makes a window modal, is left for the About dialog.

$ wish app_window.tcl
second window exists: 1
status: Note window opened
parent: .

Preferences saved to a file

Preferences make an application feel familiar: the window reopens at the size the user chose, with the same font and the last file. A plain text file is enough for this. The script reads the file with open, read and close, and writes it back with puts. Defaults protect the program against a missing file.

preferences.tcl
# preferences.tcl - keep window settings in a small text file
set prefs_file [file join [pwd] notes.conf]

proc read_prefs {path} {
    set defaults [dict create geometry 480x320 fontsize 12]
    if {![file exists $path]} {
        return $defaults
    }
    set fh [open $path r]
    set saved [read $fh]
    close $fh
    return [dict merge $defaults $saved]
}

proc write_prefs {path prefs} {
    set fh [open $path w]
    puts $fh $prefs
    close $fh
}

set prefs [dict create geometry 520x360 fontsize 14 last_file notes.txt]
write_prefs $prefs_file $prefs

set prefs [read_prefs $prefs_file]
puts "file: [file tail $prefs_file] ([file size $prefs_file] bytes)"
puts "geometry: [dict get $prefs geometry]"
puts "font size: [dict get $prefs fontsize]"
puts "last file: [dict get $prefs last_file]"

The file holds a Tcl dictionary, so dict get reads one setting by name. dict merge fills in the defaults for keys that an older preferences file does not contain, which means a new setting can be added without a migration step. The channel is always closed: an open channel can lose data when the interpreter exits. The Tcl file command page covers path handling, and open covers the channel modes in detail.

$ tclsh preferences.tcl
file: notes.conf (49 bytes)
geometry: 520x360
font size: 14
last file: notes.txt

An About dialog

An About dialog is a small window with a name, a version and an OK button. It should be modal: while it is open, clicks must not reach the main window. Tk builds this from toplevel, grab and a fixed size, without any extra package.

about_dialog.tcl
# about_dialog.tcl - a modal About window built from toplevel
wm title . "Notes"
wm geometry . 420x240

proc show_about {} {
    toplevel .about
    wm title .about "About Notes"
    wm transient .about .
    wm resizable .about 0 0
    wm protocol .about WM_DELETE_WINDOW close_about

    label .about.name -text "Notes 1.0" -font {Helvetica 14 bold}
    label .about.text -justify center \
        -text "A small Tk application.\nWritten for the ZetCode Tcl tutorial."
    button .about.ok -text "OK" -command close_about
    pack .about.name -pady {16 4}
    pack .about.text
    pack .about.ok -pady {12 16}

    grab set .about
    focus .about.ok
    bind .about <Return> close_about
}

proc close_about {} {
    grab release .about
    destroy .about
}

button .open -text "About" -command show_about
pack .open -expand 1

after 600 {
    show_about
    update
    puts "grab holder: [grab current]"
    after 300 {
        close_about
        puts "about still open: [winfo exists .about]"
        destroy .
    }
}

grab set .about routes all events to the dialog until grab release is called. Releasing the grab before destroying the window is required; a grab on a dead window leaves the application unable to receive input. wm resizable 0 0 keeps the layout fixed, focus .about.ok gives the keyboard to the dialog, and the <Return> binding closes it from anywhere in the window. wm protocol connects the title-bar close button to the same procedure as OK.

$ wish about_dialog.tcl
grab holder: .about
about still open: 0

Model and view

A window that reads its data straight from widgets is hard to test and hard to extend. The usual remedy is a small model: one place that owns the data, and one procedure that copies the data into the widgets. Here the model is a namespace with a list, and the view is a listbox refreshed from that list.

model_view.tcl
# model_view.tcl - the note data lives apart from the widgets
namespace eval notes {
    variable items {}
}

proc notes::add {text} {
    variable items
    lappend items $text
    return [llength $items]
}

proc notes::remove {index} {
    variable items
    set items [lreplace $items $index $index]
}

proc notes::all {} {
    variable items
    return $items
}

proc refresh {} {
    .list delete 0 end
    foreach note [notes::all] {
        .list insert end $note
    }
    .status configure -text "[llength [notes::all]] notes"
}

listbox .list
label .status -text "Ready" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x
pack .list -expand 1 -fill both

notes::add "Buy milk"
notes::add "Call the plumber"
notes::add "Finish the article"
notes::remove 1
refresh

wm title . "Notes"
wm geometry . 360x220

after 500 {
    puts "model:  [notes::all]"
    puts "view:   [join [.list get 0 end] { | }]"
    puts "status: [.status cget -text]"
    destroy .
}

notes::add and notes::remove change only the list; refresh is the only procedure that touches the listbox and the status label. A second view, such as the toplevel window from earlier, would call refresh after every change and show the same data. The model can also be written to disk with the file code from the preferences section, which keeps the widgets free of storage details. Namespaces are explained on the Tcl namespace page.

$ wish model_view.tcl
model:  {Buy milk} {Finish the article}
view:   Buy milk | Finish the article
status: 2 notes

Clean exit with wm protocol

The title-bar close button does not run the Quit command. The window manager asks the application to close by sending WM_DELETE_WINDOW, and Tk runs whatever script is registered for that message. Registering a procedure there is how an application saves its state before it disappears.

clean_exit.tcl
# clean_exit.tcl - save the window state before the application closes
wm title . "Notes"
wm geometry . 420x260
set state_file [file join [pwd] notes.state]

proc save_state {} {
    global state_file
    set fh [open $state_file w]
    puts $fh "geometry [wm geometry .]"
    close $fh
}

proc on_close {} {
    global state_file
    save_state
    set fh [open $state_file r]
    set saved [string trim [read $fh]]
    close $fh
    puts "saved: $saved"
    puts "closing the main window"
    destroy .
}

wm protocol . WM_DELETE_WINDOW on_close

label .hint -text "Close the window with the title bar button." \
    -wraplength 360 -justify center
button .quit -text "Quit" -command on_close
pack .hint -expand 1
pack .quit -pady 10

puts "close handler: [wm protocol . WM_DELETE_WINDOW]"
after 600 on_close

The handler writes the geometry, reads it back for the message, and destroys the main window. destroy . ends the event loop and the interpreter exits; exit would do the same but would skip the events still in the queue. Called without a script, wm protocol . WM_DELETE_WINDOW returns the registered command, which is how this example confirms the registration. The timer at the end calls the same procedure that a desktop window manager would call, so the script can be tested without a mouse.

$ wish clean_exit.tcl
close handler: on_close
saved: geometry 420x260+0+0
closing the main window

Packaging the application as a single script

A single file is the simplest way to distribute a Tk application. The shebang line lets the file run as a program on Unix, and info script returns the path of the running file, so resources can be found next to it instead of in the current directory. The script below combines the parts from the previous sections.

notes.tcl
#!/usr/bin/env wish
# notes.tcl - the whole application in one file
wm title . "Notes"
wm geometry . 480x320

set app_dir [file dirname [info script]]
set state_file [file join $app_dir notes.state]

proc set_status {text} {
    .status configure -text $text
}

proc save_state {} {
    global state_file
    set fh [open $state_file w]
    puts $fh [wm geometry .]
    close $fh
}

proc on_close {} {
    global state_file
    save_state
    puts "state written to [file tail $state_file]"
    destroy .
}

menu .menubar -tearoff 0
menu .menubar.file -tearoff 0
menu .menubar.help -tearoff 0

.menubar.file add command -label "New note" -command {
    .body delete 1.0 end
    set_status "New note"
}
.menubar.file add command -label "Count words" -command {
    set_status "[llength [split [.body get 1.0 end]]] words"
}
.menubar.file add separator
.menubar.file add command -label "Quit" -command on_close
.menubar.help add command -label "About Notes" -command {
    set_status "Notes 1.0 - a single-file Tk application"
}
.menubar add cascade -label File -menu .menubar.file
.menubar add cascade -label Help -menu .menubar.help
. configure -menu .menubar

label .status -text "Ready" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x

text .body -wrap word -undo 1
.body insert end "Buy milk\nCall the plumber\nFinish the article\n"
pack .body -expand 1 -fill both

wm protocol . WM_DELETE_WINDOW on_close

after 600 {
    set_status "Three notes, one script"
    puts "status: [.status cget -text]"
    after 300 on_close
}

file dirname [info script] gives the folder that contains the script, and file join builds the path of the state file from it. When the program is started by its full path, its state file stays next to it instead of following the current directory. After chmod +x notes.tcl, the file can be started with ./notes.tcl on a system where wish is in the search path. When the program outgrows one file, the procedures can move into modules loaded with source or package require; the structure in this article does not change.

$ wish notes.tcl
status: Three notes, one script
state written to notes.state

Source

The official manuals document the window manager commands, the menu widget and the Tk widgets used here. The Tcl manual covers the file and dictionary commands that the application relies on.

This article built the structure of a Tk application: a window skeleton, menu bar and toolbar, status bar, secondary windows, a preferences file, an About dialog, a model separated from its view, and a close handler that saves state. The file and open pages cover the storage commands, and exit describes the other way to end a Tcl program.

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.