Tcl/Tk GUI Example with Variable Input by User

[This article was first published on theBioBucket*, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

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 their blog: theBioBucket*.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)