Tcl/Tk GUI Example with Variable Input by User

August 11, 2012
By

(This article was first published on theBioBucket*, and kindly contributed to R-bloggers)

I recently used R with GUI-elements for the first time and browsed through the available online resources, but I didn't quite find what I was searching for: The user should be able to put in some variables and call a function with a button. In the end I did it with a little help from SO. Here is the working example that I eventually plugged together:

 


require(tcltk)
mydialog <- function(){

       xvar <- tclVar("")
       yvar <- tclVar("")
       zvar <- tclVar("")

       tt <- tktoplevel()
       tkwm.title(tt,"MYTEST")
       x.entry <- tkentry(tt, textvariable=xvar)
       y.entry <- tkentry(tt, textvariable=yvar)
       z.entry <- tkentry(tt, textvariable=zvar)

       reset <- function() {
         tclvalue(xvar)<-""
         tclvalue(yvar)<-""
         tclvalue(zvar)<-""
        }

       reset.but <- tkbutton(tt, text="Reset", command=reset)

       submit <- function() {
         x <- as.numeric(tclvalue(xvar))
         y <- as.numeric(tclvalue(yvar))
         z <- as.numeric(tclvalue(zvar))
         tkmessageBox(message=paste("x + y + z = ", x+y+z, ""))
       }
       submit.but <- tkbutton(tt, text="submit", command=submit)
      
       quit.but <- tkbutton(tt, text = "Close Session",
           command = function() {
           q(save = "no")
           tkdestroy(tt)
           }
        )

       tkgrid(tklabel(tt,text="Put your variables.."),columnspan=3, pady = 10)
       tkgrid(tklabel(tt,text="x variable"), x.entry, pady= 10, padx= 10)
       tkgrid(tklabel(tt,text="y variable"), y.entry, pady= 10, padx= 10)
       tkgrid(tklabel(tt,text="z variable"), z.entry, pady= 10, padx= 10)
       tkgrid(submit.but, reset.but, quit.but, pady= 10, padx= 10)

    }

mydialog()

To leave a comment for the author, please follow the link and comment on his blog: theBioBucket*.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.