multiple comboboxes in R using tcltk

会有一股神秘感。 提交于 2019-11-29 08:17:46

Why don't you just use ttkcombobox?

require(tcltk)
tt <- tktoplevel()
tkwm.title(tt, "Fruits!")
tkwm.geometry(tt, "200x150+300+300") 

onOK <- function()
    {
    fav <- tclvalue(favFruit)
    worst <- tclvalue(worstFruit)

    if (fav != "Choose one")
        tkmessageBox(title="Favorite fruit", message = paste("Your favorite fruit is", fav))
    if (worst != "Choose one")
        tkmessageBox(title="Worst fruit", message = paste("The fruit you like the least is", worst))

    if (fav == "Choose one" & worst == "Choose one")
        tkmessageBox(title="Well...", message = "Select a fruit!")
    }

label1 <- tklabel(tt, text="What's your favorite fruit?")
label2 <- tklabel(tt, text="What fruit you like the least?")

fruits <- c("Choose one", "Apple", "Orange", "Banana", "Pear")
# Default selections for the two combo boxes
favFruit <- tclVar("Choose one")
worstFruit <- tclVar("Choose one")

# 1st box
combo.1 <- ttkcombobox(tt, values=fruits, textvariable=favFruit, state="readonly") 
# 2nd box
combo.2 <- ttkcombobox(tt, values=fruits, textvariable=worstFruit, state="readonly") 
# If you need to do something when the user changes selection just use
# tkbind(combo.1, "<<ComboboxSelected>>", functionname)

OK.but <- tkbutton(tt,text="   OK   ", command = onOK)

tkpack(label1, combo.1)
tkpack(label2, combo.2)
tkpack(OK.but)

tkfocus(tt)

PS: personally, I abandoned tcltk in favour of RGtk2, much more flexible in my opinion and you can design interfaces visually using Glade Interface Designer

If you don't want to get too involved with tcltk, you might find gWidgets easier to work with.

library(gWidgets)
options(guiToolkit="tcltk") ## or RGtk2 or Qt

w <- gwindow("Multiple comboboxes")
tbl <- glayout(cont=w, horizontal=FALSE)

fruit <- c("Apple","Orange","Banana","Pear")


tbl[1,1] <- "Favorite fuits"
tbl[1,2] <- (cb1 <- gcombobox(fruit, cont=tbl))

tbl[2,1] <- "Other fruit?"
tbl[2,2] <- (cb2 <- gcombobox(fruit, cont=tbl))

tbl[3,2] <- (b <- gbutton("Ok", cont=tbl))

addHandlerClicked(b, handler=function(h,...) {
  cat(sprintf("You picked %s and %s\n", svalue(cb1), svalue(cb2)))
})
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!