简体   繁体   中英

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 ?

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM