A button that triggers a function call

A button that triggers a function call

James Wettenhall & Philippe Grosjean bio photo By James Wettenhall & Philippe Grosjean

The following R code maps the OK button of a Tk toplevel window to a R function which displays a message box. We give a minimum size of six characters for the button (by using a negative value for its width).


pressedOK <- function()
tkmessageBox(message = "You pressed OK!")

win1 <- tktoplevel() # Create a new Tk window
win1$env$butOK <- tk2button(win1, text = "OK", width = -6, command = pressedOK)
tkgrid(win1$env$butOK, padx = 20, pady = 15) # Place the button on the window

The toplevel window is shown below. We have not given it a title (using tktitle() or tkwm.title()), so the title bar displays the Tcl ID for this window, which is 1 in this case.

OK button

The result of pressing OK is shown below:

OK button pressed

To close the tk window from within R, use:

tkdestroy(win1)       # Kill the 'win1' Tk window