从 R 中的 TclTk GUI 返回变量

标签 r tcl tk-toolkit

我按照 TclTk 示例创建了一个列表框,让用户选择他们最喜欢的水果(请参见下面的代码)。该示例打印了用户的选择,仅此而已。但是,我想稍后在脚本中使用该选择来执行各种操作(在绘图标题、文件名等中使用它)。如何将用户的选择从 TclTk GUI 返回到脚本的其余部分?

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))

最佳答案

How do I return the user's choice from a TclTk GUI to the rest of my script?

这取决于你想做什么

选项 1:

如果您不再需要 GUI,则可以在从 R 变量中的 GUI 中提取所选设置后销毁它。这正是您在 onOK“事件处理程序”函数中所做的事情。

您应该添加以下 R 命令来等待 tcltk 窗口 在继续执行此行之后的 R 代码之前要关闭:

# Wait for the window to be closed
tkwait.window(win1)

然后,您可以在业务逻辑中使用 R 变量中的值(从事件处理函数中的 GUI 设置填充)。 G。通过在代码末尾添加业务逻辑代码:

choice <- tkmessageBox(message=paste("Do you want to buy", fruitChoice, "now?"), type = "yesno", icon="question")

选项 2:

您的业务逻辑在事件处理函数中触发(执行)(无需销毁/关闭窗口)以可视化业务逻辑的输出(“状态更改”)。

在这个 GUI 驱动范例中,您可以直接将业务逻辑代码添加到事件处理函数中,而无需调用 tkdestroy

要关闭窗口,您可以添加“退出”、“关闭”、“取消”...按钮。在这些按钮的事件处理函数中,您调用tkdestroy

关于从 R 中的 TclTk GUI 返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39522538/

相关文章:

TclOO : Difference between declaring variable as "class" level or in constructor

time - 如何以毫秒获取当前时间

python - 是否可以在 python tkcalendar 的日期中嵌入自定义文本

r - 如何自动绘制具有相同行数和列数的多个 CSV 文件?

r - S4 类的错误处理

list - 使用 TCL 查找字典中值的最大绝对值

python - 无法将变量传递给 python 中的 Tkinter

python - 在文本小部件中重新绑定(bind) "select all"

R - 逗号分隔的列表之间是否至少有一个匹配项?

r - 在 Shiny 中无错误地下载 react 对象