Tk text editor project
last modified November 24, 2026 Tcl 8.6
The text widget is the most capable widget in Tk. It stores
characters, marks and tags, supports undo and selection, and can be styled per
character. Those features are enough to build a complete text editor without
any third-party package. This article does exactly that, in stages: a window
with the text widget, menus, a toolbar, file handling, a status bar, search
and a safe close.
Every stage is a runnable script. The last section joins the stages into one file of about two hundred lines, split into three listings so no listing grows too long. The examples target Tk 8.6; most close themselves with a timer so they can run without a person, while the finished editor keeps its window open in the event loop.
The window and the text widget
The text widget is the engine of the editor. It holds the document, keeps the
insertion mark, and reports positions as line.column indices. Two
commands connect it to a scrollbar: yview scrolls the widget and
-yscrollcommand tells the scrollbar what part of the document is
visible.
# editor_window.tcl - one text widget, one scrollbar, nothing else
wm title . "Scratchpad"
wm geometry . 560x380
text .editor -wrap none -undo 1 -font {Courier 11}
scrollbar .scroll -command {.editor yview}
.editor configure -yscrollcommand {.scroll set}
grid .editor -row 0 -column 0 -sticky nsew
grid .scroll -row 0 -column 1 -sticky ns
grid rowconfigure . 0 -weight 1
grid columnconfigure . 0 -weight 1
.editor insert end "First line\nSecond line\nThird line"
focus .editor
after 500 {
puts "end index: [.editor index end]"
puts "first line: [.editor get 1.0 1.end]"
puts "third line: [.editor get 3.0 3.end]"
puts "characters: [.editor count -chars 1.0 end]"
destroy .
}
The window uses grid because the scrollbar must stay at the right
edge while the text area grows in both directions; the row and column weights
do that. The widget always keeps one newline after the last character, so three
lines end at index 4.0 and the document contains 34 characters
rather than 33. get reads a range and count -chars
measures one. focus .editor sends the keyboard to the text. The
Tk text widget page covers its indices and tags in
more detail.
$ wish editor_window.tcl end index: 4.0 first line: First line third line: Third line characters: 34
Menus for File, Edit and Help
An editor follows the usual menu layout: File manages documents, Edit changes
the buffer, Help explains the program. The Edit entries use virtual events
such as <<Cut>>, the same events Tk's own key bindings
generate, so the menu and the keyboard run the same code. The two explicit
bind calls at the bottom show how a shortcut is added.
# editor_menu.tcl - a menu bar with File, Edit and Help
wm title . "Scratchpad"
wm geometry . 560x380
text .editor -wrap none -undo 1 -font {Courier 11}
scrollbar .scroll -command {.editor yview}
.editor configure -yscrollcommand {.scroll set}
grid .editor -row 0 -column 0 -sticky nsew
grid .scroll -row 0 -column 1 -sticky ns
grid rowconfigure . 0 -weight 1
grid columnconfigure . 0 -weight 1
menu .menubar -tearoff 0
menu .menubar.file -tearoff 0
menu .menubar.edit -tearoff 0
menu .menubar.help -tearoff 0
.menubar.file add command -label "New" -accelerator "Ctrl+N" \
-command {.editor delete 1.0 end}
.menubar.file add command -label "Open..." -accelerator "Ctrl+O" \
-command {puts "open requested"}
.menubar.file add command -label "Save" -accelerator "Ctrl+S" \
-command {puts "save requested"}
.menubar.file add separator
.menubar.file add command -label "Exit" -command exit
.menubar.edit add command -label "Undo" -accelerator "Ctrl+Z" \
-command {.editor edit undo}
.menubar.edit add separator
.menubar.edit add command -label "Cut" -accelerator "Ctrl+X" \
-command {event generate .editor <<Cut>>}
.menubar.edit add command -label "Copy" -accelerator "Ctrl+C" \
-command {event generate .editor <<Copy>>}
.menubar.edit add command -label "Paste" -accelerator "Ctrl+V" \
-command {event generate .editor <<Paste>>}
.menubar.edit add command -label "Select all" -accelerator "Ctrl+A" \
-command {.editor tag add sel 1.0 end}
.menubar.help add command -label "About Scratchpad" \
-command {puts "Scratchpad 1.0"}
.menubar add cascade -label File -menu .menubar.file
.menubar add cascade -label Edit -menu .menubar.edit
.menubar add cascade -label Help -menu .menubar.help
. configure -menu .menubar
bind . <Control-n> {.editor delete 1.0 end}
bind . <Control-a> {.editor tag add sel 1.0 end}
.editor insert end "First line\nSecond line"
after 500 {
puts "File items: [expr {[.menubar.file index end] + 1}]"
puts "Edit items: [expr {[.menubar.edit index end] + 1}]"
.menubar.file invoke 0
puts "after New: [.editor count -chars 1.0 end] character left"
destroy .
}
add command adds an item, add separator a dividing
line, and add cascade a submenu. The accelerator strings are only
labels; the bind lines below the menus do the actual work, and
they are attached to the main window so they fire while the text has focus.
invoke runs a menu entry from code, which is how the example
tests New. The file count includes the separator, and the buffer keeps one
newline after New clears it.
$ wish editor_menu.tcl File items: 5 Edit items: 6 after New: 1 character left
A toolbar with ttk::button
A toolbar puts the three or four most frequent commands within reach. The
buttons are ttk::button widgets, which use the native theme, and a
vertical ttk::separator divides the file actions from the search
action. A button stores one command, exactly as a menu item does; in the
finished editor both call the same procedures.
# editor_toolbar.tcl - buttons that call the same commands as the menus
wm title . "Scratchpad"
wm geometry . 560x380
proc new_file {} {
.editor delete 1.0 end
.status configure -text "New document"
}
frame .toolbar
ttk::button .toolbar.new -text "New" -command new_file
ttk::button .toolbar.open -text "Open" -command {puts "open requested"}
ttk::button .toolbar.save -text "Save" -command {puts "save requested"}
ttk::separator .toolbar.sep -orient vertical
ttk::button .toolbar.find -text "Find" -command {puts "find requested"}
pack .toolbar.new .toolbar.open .toolbar.save -side left -padx 3 -pady 3
pack .toolbar.sep -side left -fill y -padx 6 -pady 5
pack .toolbar.find -side left -padx 3 -pady 3
pack .toolbar -side top -fill x
label .status -text "Ready" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x
text .editor -wrap none -undo 1
pack .editor -expand 1 -fill both
.editor insert end "Toolbar buttons call the same procedures as the menu."
after 400 {
.toolbar.new invoke
puts "status: [.status cget -text]"
puts "empty: [.editor count -chars 1.0 end] character"
puts "toolbar children: [llength [winfo children .toolbar]]"
destroy .
}
The toolbar is a frame packed across the top; the buttons are packed inside it
from the left. A ttk::button has an invoke method, so
the example can press New without a mouse. The same method is used by tests in
real applications. A button can be disabled with state disabled
when its command makes no sense, for example Save on an unchanged document.
$ wish editor_toolbar.tcl status: New document empty: 1 character toolbar children: 5
Opening a file
Opening a file is two operations: choosing a path and loading it. Tk provides
the chooser with tk_getOpenFile, which returns a path or an empty
string when the user cancels. The loading itself belongs in a separate
procedure so the program can also reopen the last file at startup without a
dialog.
# open_file.tcl - load a text file into the editor
wm title . "Scratchpad"
wm geometry . 560x380
set current_file ""
proc load_file {path} {
global current_file
set fh [open $path r]
set content [read $fh]
close $fh
.editor delete 1.0 end
.editor insert end $content
set current_file $path
wm title . "Scratchpad - [file tail $path]"
return [string length $content]
}
proc open_file {} {
set path [tk_getOpenFile -title "Open a text file" -parent .]
if {$path eq ""} { return }
puts "loaded [load_file $path] bytes"
}
text .editor -wrap none -undo 1
pack .editor -expand 1 -fill both
# demo driver: create a sample, load it without a dialog, then close
after 400 {
set sample [file join [pwd] sample.txt]
set fh [open $sample w]
puts $fh "Shopping list\nmilk\nbread\ncoffee"
close $fh
puts "loaded [load_file $sample] characters"
puts "title: [wm title .]"
puts "last line: [.editor get 4.0 4.end]"
file delete $sample
destroy .
}
load_file opens the channel, reads the whole document and closes
it before touching the widget. file tail reduces the path to the
file name for the title bar, and the procedure returns the size in characters.
open_file adds only the dialog and the cancel check. The comment
at the bottom marks the test driver, which calls load_file
directly because a dialog cannot be answered in an automated run. That driver
creates a small sample file in the current directory, loads it, and removes it
again. The open and file pages
document the channel and path commands.
$ wish open_file.tcl loaded 32 characters title: Scratchpad - sample.txt last line: coffee
Saving a file
Saving reverses the operation: the buffer is converted back to a string and
written with open in write mode. Save writes to the current path;
Save As asks for a new one. A text widget always holds a final newline, so the
program must drop that newline or every save would add a blank line.
# save_file.tcl - write the editor contents back to disk
wm title . "Scratchpad"
set current_file ""
proc save_file {path} {
global current_file
set content [.editor get 1.0 "end - 1 chars"]
set fh [open $path w]
puts -nonewline $fh $content
close $fh
set current_file $path
wm title . "Scratchpad - [file tail $path]"
return [file size $path]
}
proc save {} {
global current_file
if {$current_file eq ""} {
save_as
} else {
puts "saved [save_file $current_file] bytes"
}
}
proc save_as {} {
set path [tk_getSaveFile -title "Save the file" -parent .]
if {$path eq ""} { return }
puts "saved [save_file $path] bytes"
}
text .editor -wrap none -undo 1
pack .editor -expand 1 -fill both
.editor insert end "Shopping list\nmilk\nbread"
# demo driver: save the buffer under a name, then report what happened
after 400 {
set out [file join [pwd] output.txt]
puts "saved [save_file $out] bytes"
puts "title: [wm title .]"
puts "first line: [.editor get 1.0 1.end]"
destroy .
}
get 1.0 "end - 1 chars" returns everything except the mandatory
trailing newline. Opening a file with w truncates it, and
close flushes the data to disk; file size then
confirms how many bytes were written. save falls back to
save_as when the document has no path yet, which is the state of
a new document. The example inserts three lines and saves them to
output.txt in the current directory, so it needs no input file.
$ wish save_file.tcl saved 24 bytes title: Scratchpad - output.txt first line: Shopping list
A status bar with line and column
A status bar tells the writer where the cursor is. Tk reports the insertion
point as a line.column index, with columns counted from zero,
while people count from one. The status bar adds one to the column and shows
both numbers. It is updated after a key press or a mouse click.
# editor_status.tcl - report the cursor position in a status bar
wm title . "Scratchpad"
wm geometry . 560x380
proc update_status {} {
set pos [.editor index insert]
lassign [split $pos .] line column
.status configure -text "Line $line, Column [expr {$column + 1}]"
}
label .status -text "Line 1, Column 1" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x
frame .main
pack .main -expand 1 -fill both
text .editor -wrap none -undo 1 -font {Courier 11}
scrollbar .scroll -command {.editor yview}
.editor configure -yscrollcommand {.scroll set}
grid .editor -in .main -row 0 -column 0 -sticky nsew
grid .scroll -in .main -row 0 -column 1 -sticky ns
grid rowconfigure .main 0 -weight 1
grid columnconfigure .main 0 -weight 1
.editor insert end "First line\nSecond line\nThird line"
bind .editor <KeyRelease> update_status
bind .editor <ButtonRelease-1> update_status
bind .editor <B1-Motion> update_status
focus .editor
after 400 {
.editor mark set insert 2.4
update_status
puts "status: [.status cget -text]"
.editor insert insert "very "
update_status
puts "status: [.status cget -text]"
destroy .
}
index insert returns the position of the insertion mark, and
lassign splits it into the two numbers. Three bindings cover the
usual ways of moving the cursor: <KeyRelease> for typing,
<ButtonRelease-1> for a click, and
<B1-Motion> for dragging a selection. The label is packed at
the bottom before the editor, so it keeps its place when the window is resized.
$ wish editor_status.tcl status: Line 2, Column 5 status: Line 2, Column 10
Find and replace
The text widget has a search subcommand, so the widget itself can
find text without a separate index. It returns the index of the next match or
an empty string.
With -nocase the search ignores case, and -count
reports the length of the match, which is what the selection needs.
# editor_find.tcl - find and replace across the whole buffer
wm title . "Scratchpad"
wm geometry . 640x400
set last_pos 1.0
proc find_next {} {
global last_pos
set needle [.find.what get]
if {$needle eq ""} { return }
set found [.editor search -nocase -count length -- $needle $last_pos end]
if {$found eq ""} {
set last_pos 1.0
set found [.editor search -nocase -count length -- $needle 1.0 end]
}
if {$found eq ""} {
.status configure -text "Not found: $needle"
return
}
.editor tag remove sel 1.0 end
.editor tag add sel $found "$found + $length chars"
.editor mark set insert $found
.editor see $found
set last_pos "$found + 1 chars"
.status configure -text "Found at $found"
}
proc replace_all {} {
set what [.find.what get]
set with [.find.replace get]
if {$what eq ""} { return }
set count 0
set pos 1.0
while {1} {
set found [.editor search -nocase -- $what $pos end]
if {$found eq ""} { break }
.editor delete $found "$found + [string length $what] chars"
.editor insert $found $with
set pos "$found + [string length $with] chars"
incr count
}
.status configure -text "$count replaced"
}
frame .find
label .find.what_lbl -text "Find:"
entry .find.what -width 18
label .find.with_lbl -text "Replace:"
entry .find.replace -width 18
ttk::button .find.next -text "Find next" -command find_next
ttk::button .find.all -text "Replace all" -command replace_all
pack .find.what_lbl .find.what .find.with_lbl .find.replace \
.find.next .find.all -side left -padx 3 -pady 4
pack .find -side top -fill x
label .status -text "Ready" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x
text .editor -wrap none -undo 1 -font {Courier 11}
pack .editor -expand 1 -fill both
.editor insert end "The quick brown fox\njumps over the lazy dog\nThe fox sleeps."
# demo driver: replace every fox, then search for the new word
after 400 {
.find.what insert 0 "fox"
.find.replace insert 0 "cat"
replace_all
puts "status: [.status cget -text]"
puts "line 1: [.editor get 1.0 1.end]"
puts "line 3: [.editor get 3.0 3.end]"
.find.what delete 0 end
.find.what insert 0 "cat"
find_next
puts "status: [.status cget -text]"
destroy .
}
find_next searches from the last match, wraps to the start when
nothing follows, and highlights the result with the sel tag.
replace_all deletes each match and inserts the replacement, then
continues after the new text. Advancing past the replacement is essential:
replacing a with aa would otherwise find the same
spot forever. Both procedures report through the status bar instead of opening
a message box.
$ wish editor_find.tcl status: 2 replaced line 1: The quick brown cat line 3: The cat sleeps. status: Found at 1.16
A clean close and exit
Closing an editor must not throw away unsaved work. The text widget tracks
whether its content changed, and Tk generates <<Modified>>
when that flag changes. The editor copies the flag into a variable, marks the
title with an asterisk, and saves on the way out.
# editor_close.tcl - save unsaved work before the window disappears
wm title . "Scratchpad"
wm geometry . 480x300
set current_file [file join [pwd] session.txt]
set dirty 0
proc save_text {path} {
set fh [open $path w]
puts -nonewline $fh [.editor get 1.0 "end - 1 chars"]
close $fh
.editor edit modified 0
set ::dirty 0
wm title . "Scratchpad - [file tail $path]"
return [file size $path]
}
proc mark_dirty {} {
set ::dirty [.editor edit modified]
set name [file tail $::current_file]
if {$::dirty} {
wm title . "Scratchpad - $name*"
} else {
wm title . "Scratchpad - $name"
}
}
proc on_close {} {
if {$::dirty} {
puts "changes pending: [save_text $::current_file] bytes saved"
} else {
puts "no changes to save"
}
destroy .
}
wm protocol . WM_DELETE_WINDOW on_close
text .editor -undo 1 -font {Courier 11}
pack .editor -expand 1 -fill both
.editor insert end "Draft of the closing section."
.editor edit modified 0
bind .editor <<Modified>> mark_dirty
# demo driver: edit, let the modified event fire, then close the window
after 400 {
.editor insert end "\nSecond thought."
update
puts "dirty: $dirty"
puts "title: [wm title .]"
on_close
}
edit modified returns 1 after the first change and can be reset
with edit modified 0 after a save or a load. The
<<Modified>> binding fires when the flag changes, not
on every keystroke, so it is cheap. The example calls update so
the event is delivered before it prints the state. on_close saves
a document that has a path and always destroys the window; a document without
a path would need a tk_messageBox question, which is left out
because it would block an automated run. wm protocol wires the
title-bar button to the same handler.
$ wish editor_close.tcl dirty: 1 title: Scratchpad - session.txt* changes pending: 45 bytes saved
Putting the pieces together
The final program combines the parts. The first listing holds the state variables and the procedures that read and write files. The second adds the menus, toolbar, status bar and the text widget itself. The third adds search and the close handler. The pieces are shown in order; together they form one file.
#!/usr/bin/env wish
# editor.tcl - a small text editor in one file
wm title . "Scratchpad"
wm geometry . 700x460
set current_file ""
set dirty 0
proc load_file {path} {
set fh [open $path r]
set content [read $fh]
close $fh
.editor delete 1.0 end
.editor insert end $content
.editor edit modified 0
set ::current_file $path
set ::dirty 0
update_title
set_status "Loaded [file tail $path]"
}
proc save_file {path} {
set fh [open $path w]
puts -nonewline $fh [.editor get 1.0 "end - 1 chars"]
close $fh
.editor edit modified 0
set ::current_file $path
set ::dirty 0
update_title
set_status "Saved [file tail $path]"
}
proc save {} {
if {$::current_file eq ""} {
save_as
} else {
save_file $::current_file
}
}
proc save_as {} {
set path [tk_getSaveFile -parent . -title "Save the file"]
if {$path eq ""} { return }
save_file $path
}
proc open_file {} {
set path [tk_getOpenFile -parent . -title "Open a text file"]
if {$path eq ""} { return }
load_file $path
}
proc set_status {text} {
.status configure -text $text
}
proc update_title {} {
set name "Untitled"
if {$::current_file ne ""} {
set name [file tail $::current_file]
}
if {$::dirty} {
wm title . "Scratchpad - $name*"
} else {
wm title . "Scratchpad - $name"
}
}
proc new_file {} {
.editor delete 1.0 end
set ::current_file ""
set ::dirty 0
update_title
set_status "New document"
}
The file procedures set both the document and the window title, and they clear
the modified flag because the buffer now matches the disk. save
chooses between the current path and the Save As dialog, while
open_file wraps the chooser around load_file. The
leading #!/usr/bin/env wish line makes the finished file
executable on Unix.
proc update_status {} {
lassign [split [.editor index insert] .] line column
set_status "Line $line, Column [expr {$column + 1}]"
}
proc on_modified {} {
set ::dirty [.editor edit modified]
update_title
update_status
}
menu .menubar -tearoff 0
menu .menubar.file -tearoff 0
menu .menubar.edit -tearoff 0
menu .menubar.help -tearoff 0
.menubar.file add command -label "New" -accelerator "Ctrl+N" -command new_file
.menubar.file add command -label "Open..." -accelerator "Ctrl+O" -command open_file
.menubar.file add command -label "Save" -accelerator "Ctrl+S" -command save
.menubar.file add command -label "Save as..." -command save_as
.menubar.file add separator
.menubar.file add command -label "Exit" -command on_close
.menubar.edit add command -label "Undo" -accelerator "Ctrl+Z" \
-command {.editor edit undo}
.menubar.edit add separator
.menubar.edit add command -label "Cut" -accelerator "Ctrl+X" \
-command {event generate .editor <<Cut>>}
.menubar.edit add command -label "Copy" -accelerator "Ctrl+C" \
-command {event generate .editor <<Copy>>}
.menubar.edit add command -label "Paste" -accelerator "Ctrl+V" \
-command {event generate .editor <<Paste>>}
.menubar.edit add command -label "Select all" -accelerator "Ctrl+A" \
-command {.editor tag add sel 1.0 end}
.menubar.help add command -label "About Scratchpad" \
-command {set_status "Scratchpad 1.0 - a Tk text editor"}
.menubar add cascade -label File -menu .menubar.file
.menubar add cascade -label Edit -menu .menubar.edit
.menubar add cascade -label Help -menu .menubar.help
. configure -menu .menubar
bind . <Control-n> new_file
bind . <Control-o> open_file
bind . <Control-s> save
frame .toolbar
ttk::button .toolbar.new -text "New" -command new_file
ttk::button .toolbar.open -text "Open" -command open_file
ttk::button .toolbar.save -text "Save" -command save
ttk::separator .toolbar.sep -orient vertical
ttk::button .toolbar.find -text "Find" -command {focus .find.what}
pack .toolbar.new .toolbar.open .toolbar.save -side left -padx 3 -pady 3
pack .toolbar.sep -side left -fill y -padx 6 -pady 5
pack .toolbar.find -side left -padx 3 -pady 3
pack .toolbar -side top -fill x
frame .find
label .find.what_lbl -text "Find:"
entry .find.what -width 16
label .find.with_lbl -text "Replace:"
entry .find.replace -width 16
ttk::button .find.next -text "Find next" -command find_next
ttk::button .find.all -text "Replace all" -command replace_all
pack .find.what_lbl .find.what .find.with_lbl .find.replace \
.find.next .find.all -side left -padx 3 -pady 4
pack .find -side top -fill x
label .status -text "Ready" -anchor w -relief sunken -bd 1
pack .status -side bottom -fill x
This part builds the visible application: menu bar, key bindings, toolbar and find bar, then the editor with its scrollbar and bindings. The menu commands refer to procedures from the first part and to the search procedures from the third; Tcl resolves the names when a command runs, not when the menu is built, so the order of the three parts is not a problem.
frame .main
pack .main -expand 1 -fill both
text .editor -wrap none -undo 1 -font {Courier 11}
scrollbar .scroll -command {.editor yview}
.editor configure -yscrollcommand {.scroll set}
grid .editor -in .main -row 0 -column 0 -sticky nsew
grid .scroll -in .main -row 0 -column 1 -sticky ns
grid rowconfigure .main 0 -weight 1
grid columnconfigure .main 0 -weight 1
bind .editor <<Modified>> on_modified
bind .editor <KeyRelease> update_status
bind .editor <ButtonRelease-1> update_status
focus .editor
set last_pos 1.0
proc find_next {} {
global last_pos
set needle [.find.what get]
if {$needle eq ""} { return }
set found [.editor search -nocase -count length -- $needle $last_pos end]
if {$found eq ""} {
set last_pos 1.0
set found [.editor search -nocase -count length -- $needle 1.0 end]
}
if {$found eq ""} {
set_status "Not found: $needle"
return
}
.editor tag remove sel 1.0 end
.editor tag add sel $found "$found + $length chars"
.editor mark set insert $found
.editor see $found
set last_pos "$found + 1 chars"
set_status "Found at $found"
}
proc replace_all {} {
set what [.find.what get]
set with [.find.replace get]
if {$what eq ""} { return }
set count 0
set pos 1.0
while {1} {
set found [.editor search -nocase -- $what $pos end]
if {$found eq ""} { break }
.editor delete $found "$found + [string length $what] chars"
.editor insert $found $with
set pos "$found + [string length $with] chars"
incr count
}
set_status "$count replaced"
}
proc on_close {} {
if {$::dirty && $::current_file ne ""} {
save_file $::current_file
puts "saved [file tail $::current_file] before exit"
} else {
puts "closed without saving"
}
destroy .
}
wm protocol . WM_DELETE_WINDOW on_close
The search procedures keep their own position, and the close handler saves a
named document before destroying the window. There is no explicit loop command:
once the script has been read, wish processes events itself, so the
window stays open until on_close destroys it. The assembled program
was tested by appending a short driver that loaded a sample file, inserted a
word, replaced another word, saved the result and closed the window; it reported
the saved size and the updated title without errors. The
file page covers the storage commands and
after explains timers like the ones in the test
drivers.
Source
The Tk manual describes the text widget, its indices and its search subcommand, as well as the menu and ttk widgets used above. The Tcl manual documents the file and string commands that support the editor.
This article built a text editor with Tk: the text widget and its indices, a menu bar, a ttk toolbar, opening and saving files, a line and column status bar, find and replace, and a close handler that saves before exit. For the surrounding application structure, see the Tk application structure article; the open and exit pages cover two commands the editor relies on.
Author
List all Tcl Tutorials.