I've followed the TclTk example for creating a listbox to let the user choose their favorite fruit (see code below). The example prints the user's choice and that's it. However, I want to use that choice later in my script to do various things (use it in plot titles, filenames, etc.) How do I return the user's choice from a TclTk GUI to the rest of my script?
library(tcltk2)
win1 <- tktoplevel()
win1$env$lst <- tk2listbox(win1, height = 4, selectmode = "single")
tkgrid(tk2label(win1, text = "What's your favorite fruit?", justify = "left"),
padx = 10, pady =c(15, 5), sticky = "w")
tkgrid(win1$env$lst, padx = 10, pady = c(5, 10))
fruits <- c("Apple", "Orange", "Banana", "Pear", "Apricot")
for (fruit in fruits)
tkinsert(win1$env$lst, "end", fruit)
# Default fruit is Banana. Indexing starts at zero.
tkselection.set(win1$env$lst, 2)
onOK <- function() {
fruitChoice <- fruits[as.numeric(tkcurselection(win1$env$lst)) + 1]
tkdestroy(win1)
msg <- paste0("Good choice! ", fruitChoice, "s are delicious!")
tkmessageBox(message = msg)
}
win1$env$butOK <-tk2button(win1, text = "OK", width = -6, command = onOK)
tkgrid(win1$env$butOK, padx = 10, pady = c(5, 15))