Drop-down combobox

Drop-down combobox

James Wettenhall & Philippe Grosjean bio photo By James Wettenhall & Philippe Grosjean

There is a ttkcombobox() drop-down combo box widgets in tcltk, and a very similar tk2combobox() in tcltk2. The following examples illustrate how to use it in a Tk window.


win1 <- tktoplevel()
win1$env$combo <- tk2combobox(win1)
tkgrid(win1$env$combo, padx = 10, pady = 15)

# A couple of functions to interact with the combobox:
# Fill the combobox list
fruits <- c("Apple", "Orange", "Banana")
tk2list.set(win1$env$combo, fruits)
# Add one or more elements to the list
tk2list.insert(win1$env$combo, "end", "Apricot", "Pear")
# Delete, query, get the list
tk2list.delete(win1$env$combo, 3) # 0-based index!
tk2list.get(win1$env$combo) # All items
# Link current selection to a variable
fruit <- tclVar("Orange")
tkconfigure(win1$env$combo, textvariable = fruit)

# Create a button to get the content of the combobox
onOK <- function() {
msg <- paste0("Good choice! ", tclvalue(fruit), "s are delicious!")
tkmessageBox(title = "Fruit Choice", message = msg)
win1$env$butOK <- tk2button(win1, text = "OK", width = -6, command = onOK)
tkgrid(win1$env$butOK, padx = 10, pady = c(0, 15))

The code above produces the following window:


Change the selection to “Pear”…

combobox selection

… and click OK.

combobox OK