Edit Boxes in R TclTk

The following example illustrates how to use an edit box in a Tk window. Note that the Enter/Return key is mapped to have the same effect as clicking the OK button with the mouse. A common mistake is to assume that the <Enter> event corresponds to the Enter key being pressed, but this would actually mean that the user is entering data into the Tk widget (in this case the edit box). So for this example, <Return> is the correct event to capture.

require(tcltk)
tt<-tktoplevel()
Name <- tclVar("Anonymous")
entry.Name <-tkentry(tt,width="20",textvariable=Name)
tkgrid(tklabel(tt,text="Please enter your first name."))
tkgrid(entry.Name)
OnOK <- function()
{
	NameVal <- tclvalue(Name)
	tkdestroy(tt)
	msg <- paste("You have a nice name,",NameVal)
	tkmessageBox(message=msg)
}
OK.but <-tkbutton(tt,text="   OK   ",command=OnOK)
tkbind(entry.Name, "<Return>",OnOK)
tkgrid(OK.but)
tkfocus(tt)