Message boxes in R tcltk

Message boxes in R tcltk

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

The following code demonstrates a simple “Hello World” message box.

library(tcltk2) # For themed message boxes; library(tcltk) is fine too here
res <- tkmessageBox(title = "Greetings from R TclTk",
  message = "Hello, world!", icon = "info", type = "ok")

A Tk window

After pressing the OK button, we can check the return value of the message box function.

res               # This is a Tcl variable
## <Tcl> ok
tclvalue(res)     # Get the value from a Tcl variable
## [1] "ok"
as.character(res) # It works also that way
## [1] "ok"

We notice that the window size for the message box is too small to display the full title in the title bar, and unfortunately message boxes are not resizable by default (whereas tktoplevel windows are resizable by default). A simple way to fix this (which is admittedly not very elegant), is to add spaces on the end of the message to make it at least as long as the title.

res <- tkmessageBox(title = "Greetings from R TclTk",
  message = "Hello, world!                 ", icon = "info", type = "ok")

A Tk window

Of course, sometimes it is desirable to have other buttons and/or other icons in a message box. The following examples illustrate some typical choices of buttons and icons.

tkmessageBox(message = "An error has occurred!", icon = "error", type = "ok")

A Tk window

tkmessageBox(message = "This is a warning!", icon = "warning", type = "ok")

A Tk window

tkmessageBox(message = "Do you want to save before quitting?",
    icon = "question", type = "yesnocancel", default = "yes")

A Tk window