Version 7 of Text Widget Example

Updated 2002-11-20 18:24:49

There have been several posts recently on clt, concerning the use of the text widget. Since I couldn't readily find the links to the existing examples that I have seen before, well here goes:


 menu .menubar -type menubar
 .menubar add cascade -label File -menu .menubar.file -underline 0

 #file menu
 menu .menubar.file -tearoff 0
 .menubar.file add command -label "New" -underline 0 \
 -command { new } 
 .menubar.file add command -label "Open..." -underline 0 \
 -command { file_get }
 .menubar.file add command -label "Save" -underline 0 \
 -command {  save}
 .menubar.file add command -label "Save As..." -underline 5 \
 -command { file_save_as }
 .menubar.file add separator
 .menubar.file add command -label Exit -underline 1 -command { exit}
 #end file menu

 . configure -menu .menubar

 set filename "Untitled"

 frame .text
 text .text.t -wrap none \
 -yscrollcommand ".text.v_scroll set" \
 -xscrollcommand ".text.h_scroll set"

 scrollbar .text.v_scroll -command ".text.t yview"
 scrollbar .text.h_scroll -command ".text.t xview" -orient horizontal
 pack .text.v_scroll -side right -fill y
 pack .text.h_scroll -side bottom -fill x
 pack .text.t -side left -fill both -expand 1
 pack .text -fill both -expand 1

 proc new { } {
 .text.t delete 1.0 end
 set filename "Untitled"
 wm title . $filename
 }

 proc file_get { } {
 .text.t delete 1.0 end
 set file_types {
  {"Tcl Files" { .tcl .TCL .tk .TK} }
  {"Text Files" { .txt .TXT } }
  {"All Files" * }
 }
 set filename [tk_getOpenFile -filetypes $file_types -initialdir pwd]
 set filesize [file size $filename]
 set fileid [open $filename r]
 set data [read $fileid $filesize]
        close $fileid
 .text.t insert end $data
 wm title . $filename
 }

 proc save { } {
 set data [.text.t get 1.0 {end -1c}]
 set fileid [open $filename w]
 puts -nonewline $fileid $data
 close $fileid
 }

 proc file_save_as { } {
 global filename
 set data [.text.t get 1.0 {end -1c}]
 set file_types {
  {"Tcl Files" { .tcl .TCL .tk .TK} }
  {"Text Files" { .txt .TXT} }
  {"All Files" * }
 }

 set filename [tk_getSaveFile -filetypes $file_types\
 -initialdir pwd -initialfile $filename\
 -defaultextension .tcl]
 wm title . $filename
 set fileid [open $filename w]
 puts -nonewline $fileid $data
 close $fileid
 }

 tk appname "Edit"

I know this could have been even more minimalist, but thought this would answer most of the recent questions I have seen. Left one little glitch in here on purpose... Also, no error handling.

Hope this is helpful to someone. I remember (not too long ago), how long it took me to get this far working out of a book :^) so


Also, please note that the menu in the above script requires tcl/tk 8.0 or higher. There are some grab problems with this type of a menu when running Gnome. ''so'


Category GUI