Drop Down Combo Boxes in R TclTk

There are at least two drop-down combo box widgets available in Tcl/Tk. One of them is the ComboBox widget in the BWidget package, and another is the comboBox widget in the Iwidgets package. I now prefer the BWidget ComboBox widget, partly because the BWidget extension consists only of Tcl scripts (no binary shared libraries).

The BWidget and Iwidgets packages are not included in the minimal installation of Tcl/Tk which comes with R. They are available within the ActiveTcl distribution, available from here. To use these additional Tcl/Tk packages, you need to set the environment variable TCL_LIBRARY to your Tcl library path, e.g. C:\Tcl\lib\tcl8.4 and set the environment variable MY_TCLTK to a non-empty string, e.g. "Yes". You may also need to use addTclPath("C:/Tcl/lib") (in R) to tell Tcl/Tk where to find these additional packages.

The following example illustrates how to use a drop down combo box in a Tk window. This example requires R 1.8.0 or later, as the vector of fruits below would have been interpreted differently (as a list of arguments, rather than a Tcl list) in previous versions of R.

require(tcltk)
tclRequire("BWidget")
tt <- tktoplevel()
tkgrid(tklabel(tt,text="What's your favorite fruit?"))
fruits <- c("Apple","Orange","Banana","Pear")
comboBox <- tkwidget(tt,"ComboBox",editable=FALSE,values=fruits)
tkgrid(comboBox)

OnOK <- function()
{
    fruitChoice <- fruits[as.numeric(tclvalue(tkcmd(comboBox,"getvalue")))+1]
    tkdestroy(tt)
    msg <- paste("Good choice! ",fruitChoice,"s are delicious!",sep="")
    tkmessageBox(title="Fruit Choice",message=msg)

}
OK.but <-tkbutton(tt,text="   OK   ",command=OnOK)
tkgrid(OK.but)
tkfocus(tt)
The code above produces the following window: