[R] callback environment for Tk buttons

Thomas Vogels tov at ece.cmu.edu
Sat Feb 3 20:48:55 CET 2001


Hi.  I'm running into problems with using R functions as callback
commands for buttons in Tk.

The following Tcl/Tk script creates three buttons.  If you press hello
it prints hello world. If you press HALLO it prints HALLO WORLD.
Not exciting, but I need an example...

    set tt [toplevel .tt]
    foreach i {"hello" "HALLO"} {
        pack [button $tt.b$i -text $i -command "puts $i"] -fill x
    }
    pack [button $tt.dismiss -text dismiss -command "destroy $tt"] -fill x

If I translate this to R, I get:
    tt <- tktoplevel()
    for (i in c("hello", "HALLO"))
        tkpack (tkbutton (tt, text=i,
                          command=function()cat(i,"world\n")), fill="x")
    tkpack (tkbutton (tt, text="dismiss",
                      command=function()tkdestroy(tt)), fill="x")

which is dumb, because the value of i is now always "HALLO" and either
button will cause R to 'cat' HALLO world.

The second try works better:
    tt <- tktoplevel()
    for (i in c("hello", "HALLO")) {
        cb <- eval(substitute(function()cat(w,"world\n"), list(w=i)))
        tkpack (tkbutton (tt, text=i, command=cb), fill="x")
    }
    tkpack (tkbutton (tt, text="dismiss",
                      command=function()tkdestroy(tt)), fill="x")

Now cb stores the value of i in the environment that it comes with.

At last the question:  am I missing the easy way out?  Or did I jump
out of the frying pan into the fire?  I.e. out of Tcl's quoting hell
into R's scoping rules ;-)

Thanks,
  -tom

-- 
mailto:tov at ece.cmu.edu (Tom Vogels)   Tel: (412) 268-6638   FAX: -3204

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list