Tcl/Tk GUI Example with Variable Input by User

August 11, 2012

(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:


mydialog <- function(){

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

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

       reset <- function() {

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

       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)



To leave a comment for the author, please follow the link and comment on their blog: theBioBucket*. 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.