Version 0 of Widget tags

Updated 2003-02-17 13:02:02

RS 2003-02-17 - Tags, strings that represent groups of objects, are a powerful concept, used in Tk for text portions, canvas items, and for bindings in bindtags. Another use for tags, and their Tcl implementation, has been proposed by Bryan Oakley in the comp.lang.tcl newsgroup:

It's fairly easy to code up yourself, and makes for a nice little programming exercise.

A variation of what I do looks roughly like this (off of the top of my head, not tested, YMMV, void where prohibited by law, do not operate heavy machinery while using, wait two hours before going swimming, not suitable for young children, etc)

     # some typical widgets...
     .menubar.editMenu add command -label Paste ...
     .popupMenu add command -label Paste ...
     button .toolbar.paste -text Paste ...

     # associate them with a symbolic name
     associate paste .menubar.editMenu Paste
     associate paste .toolbar.paste
     associate paste .popupMenu Paste

     ....

     # enable only if there's something on the clipboard
     if {there is nothing on the clipboard} {
         disable paste
     } else {
         enable paste
     }

All that's left is to write the procs associate, enable and disable.

Associate is simple:

     proc associate {what args} {
         global widgets
         lappend widgets($what) $args
     }

enable and disable are also pretty simple:

     proc enable {what} {
         global widgets
         foreach item $widgets($what) {
             set widget [lindex $item 0]
             if {[winfo exists $widget]} {
                 if {[winfo class $widget] == "Menu"} {
                     set index [lindex $item 1]
                     $widget entryconfigure $index -state normal
                 } else {
                     $widget configure -state normal
                 }
             }
         }
     }

I've used a variation of this for years and it works great. It's a pain

   to have to associate widgets with a symbolic name, but it's worth the 

effort. Besides the obvious benefits, it makes the code easier to maintain in that if you change widget paths or add or remove widgets you only have to change the related "associate" commands rather than hunting down hard-coded widget paths throughout your code.

There are lots of things you can do to make the code even more fancy. For example, you can support accelerators, build your own widget wrappers that do the "associate" step automatically, add a disassociate step, etc.


Arts and crafts of Tcl-Tk programming