Menus in R TclTk

A Simple File Menu

The example below illustrates how to add a simple menu to a Tk toplevel window.

require(tcltk)
tt <- tktoplevel()
topMenu <- tkmenu(tt)
tkconfigure(tt,menu=topMenu)
fileMenu <- tkmenu(topMenu,tearoff=FALSE)
tkadd(fileMenu,"command",label="Quit",command=function() tkdestroy(tt))
tkadd(topMenu,"cascade",label="File",menu=fileMenu)
tkfocus(tt)

Running the code above gives the following window:





Cascading Menus Within Other Menus

The example below illustrates how to cascade menu within another menu

require(tcltk)
tt <- tktoplevel()
topMenu <- tkmenu(tt)
tkconfigure(tt,menu=topMenu)
fileMenu <- tkmenu(topMenu,tearoff=FALSE)
openRecentMenu <- tkmenu(topMenu,tearoff=FALSE)
tkadd(openRecentMenu,"command",label="Recent File 1",
    command=function() tkmessageBox(message="I don't know how to open Recent File 1",icon="error"))
tkadd(openRecentMenu,"command",label="Recent File 2",
	command=function() tkmessageBox(message="I don't know how to open Recent File 2",icon="error"))
tkadd(fileMenu,"cascade",label="Open recent file",menu=openRecentMenu)
tkadd(fileMenu,"command",label="Quit",command=function() tkdestroy(tt))
tkadd(topMenu,"cascade",label="File",menu=fileMenu)
tkfocus(tt)

Running the code above gives the following window:







Adding a Pop-Up Menu to a Text Window

The example below demonstrates how to add a simple pop-up menu to a text window. The hard part is determining the mouse coordinates in order to ensure that the menu appears where the mouse is right-clicked. Note that the keyboard shortcuts for copying and pasting (<Ctrl-C> and <Ctrl-V>) are mapped automatically for a Tk text widget.

require(tcltk)
tt <- tktoplevel()
txt <- tktext(tt)
tkgrid(txt)
copyText <- function() tkcmd("event","generate",.Tk.ID(txt),"<<Copy>>")

editPopupMenu <- tkmenu(txt, tearoff=FALSE)
tkadd(editPopupMenu, "command", label="Copy <Ctrl-C>",
command=copyText)

RightClick <- function(x,y) # x and y are the mouse coordinates
{
rootx <- as.integer(tkwinfo("rootx",txt))
rooty <- as.integer(tkwinfo("rooty",txt))
xTxt <- as.integer(x)+rootx
yTxt <- as.integer(y)+rooty
tkcmd("tk_popup",editPopupMenu,xTxt,yTxt)
}
tkbind(txt, "<Button-3>",RightClick)
tkfocus(tt)