Version 1 of tk_optionCascade

Updated 2006-12-22 13:38:40 by suchenwi

Richard Suchenwirth 2006-12-22 - The tk_optionMenu offers a handy alternative to a combobox. But for a larger number of structured choices, it is sometimes better to have cascading menus instead of one. Here's a quick hack for that. It follows the same simple API as tk_optionMenu, but if an item is a list of more than one elements, it is turned into a submenu. (Add an extra layer of braces around labels that contain spaces - see example below.) Oh, and the special item "--" makes a separator.

 proc tk_optionCascade {w varName args} {
     set dn [image create bitmap -data "#define i_width 7\n\#define i_height 5
        static char i_bits[] = {\n0,127,62,28,8\n}"]
     set it [lindex $args 0]
     while {[llength $it]>1} {set it [lindex $it 0]}
     set ::$varName $it
     menubutton $w -menu $w.m -text $it -relief raised \
         -image $dn -compound right
     menu $w.m -tearoff 0
     tk_optionCascade_add $w.m $varName $args
     trace var ::$varName w "$w config -text $$varName ;\#"
     return $w.m
 }
 proc tk_optionCascade_add {w varName argl} {
     set n 0
     foreach arg $argl {
         if {$arg eq "--"} {
             $w add separator
         } elseif {[llength $arg] == 1} {
             $w add radiobutton -label [join $arg] -variable $varName 
         } else {
             set child [menu $w.[incr n] -tearoff 0]
             $w add cascade -label [lindex $arg 0] -menu $child
             tk_optionCascade_add $child $varName [lrange $arg 1 end]
         }
     }
 }

# Demo and testing:

 package require Tk
 tk_optionCascade .o myvar \
           {color red green blue -- {other yellow magenta cyan}} \
           {hue   dark medium light} \
           -- {"multi word example"} ok
 pack .o

Category Example