rtk-toolkitrgui

tcltk R - how to access value returned by function


I just started with tcltk and R. And I am having troubles accessing a computed value by a function called myFun1 when calling a second function myFun2:

Here is a simplified version of my UI:

Simple tcltk interface

library(tcltk)
tt <- tktoplevel()
    topMenu <- tkmenu(tt)
    tkconfigure(tt, menu = topMenu)
    fileMenu <- tkmenu(topMenu, tearoff = FALSE)
        tkadd(fileMenu, "command", label = "Function1", command = myFun1)
        tkadd(fileMenu, "command", label = "Function2", command = myFun2)
        tkadd(topMenu, "cascade", label = "Tab", menu = fileMenu)
tkfocus(tt)

My functions

myFun1 <- function() { 
    compVal <- 2*3
    compVal
}

myFun2 <- function() { 
    msg <- paste("The value is: \n", compVal )
    mbval<- tkmessageBox(title="This is the title",
                     message=msg,type="yesno",icon="question")
}

Calling myFun1 works, but myFun2 returns

Error in paste("The value is: \n", compVal) : Object 'compVal' not found

Also wrapping compVal into return(compVal) doesn`t work. I was also thinking of doing:

res <- list(compVal=compVal)

but I am not able to access the created list with myFun2. Any sugesstions on how to access the returned value form myFun1 inside myFun2?


Solution

  • I found a solution, at first I thought its not really a "clean" way of doing it, but even in the offical documentation it is done this way. Simply create a global variable using <<- :

    myFun1 <- function() { 
        compVal <<- 2*3
    }