tk_optionMenu

Create an option menubutton and its menu.


http://purl.org/tcl/home/man/tcl8.4/TkCmd/optionMenu.htm

The code for this command is found in Tk's optMenu.tcl library file.

See also: optionMenu.


SYNOPSIS

tk_optionMenu w varName value ?value value …?

DESCRIPTION

This procedure creates an option menubutton whose name is w, plus an associated menu. Together they allow the user to select one of the values given by the value arguments. The current value will be stored in the global variable whose name is given by varName and it will also be displayed as the label in the option menubutton. The user can click on the menubutton to display a menu containing all of the values and thereby select a new value. Once a new value is selected, it will be stored in the variable and appear in the option menubutton. The current value can also be changed by setting the variable.

The return value from tk_optionMenu is the name of the menu associated with w, so that the caller can change its configuration options or manipulate it in other ways.

EXAMPLE

tk_optionMenu .menu globVar Val1 Val2 Val3 ValJunk
pack .menu

To put the contents from a list

set l {4 5 6}
set optname [tk_optionMenu .menu varname junk ]
pack .menu -side left
$optname delete 0
set j [llength $l]
for {set i 0} {$i < $j} {incr i} {
    set e [lindex $l $i]
    $optname insert $i radiobutton -label $e -variable menvar -command \
        {global menvar; set varname $menvar}
}

Do you want "an event binding for selecting a value from tk_optionMenu"?

Tom Wilkason pointed out in a comp.lang.tcl thread that "The most common approach is to have a trace on the linked variable."

KPV While adding a trace works, I find it easier just to configure the menu entries to call a specific command:

tk_optionMenu $w varName a b c d
for {set i 0} {$i < [[$w cget -menu] index end]} {incr i} {
  [$w cget -menu] entryconfig $i -command $cmd
}

Are there reasons why this isn't also good for adding items from a list? It works well for me and is much simpler than the above code...

 set list_of_choices {red green blue}
 eval tk_optionMenu .menu globVar $list_of_choices

DKF: It's reasonable, but you're better off with using expansion from 8.5 onwards. This then allows you to format the list of choices more flexibly:

set list_of_choices {
    red
    green
    blue
}
tk_optionMenu .menu globVar {*}$list_of_choices

RS 2007-06-26 - Examples how to tweak the appearance of an option menu:

    set menu [eval tk_optionMenu $o choices {red green blue}
    $o configure -bg white -activebackground white -pady 2 -borderwidth 1
    $menu configure -bg white

See also