File Open/Save Dialogs in R TclTk

The Open File Dialog

require(tcltk)
fileName<-tclvalue(tkgetOpenFile())
if (!nchar(fileName))
    tkmessageBox(message="No file was selected!")
else
    tkmessageBox(message=paste("The file selected was",fileName))

The code above produces the following window:





The Save File Dialog

require(tcltk)
fileName<-tclvalue(tkgetSaveFile())
if (!nchar(fileName))
    tkmessageBox(message="No file was selected!")
else
    tkmessageBox(message=paste("The file selected was",fileName))

The code above produces the following window:



Now we will assume that the user pressed Cancel:



Opening SPSS Files With The Open File Dialog

This example was contributed by Christian Schulz. It shows how to tell the OpenFile dialog what type of files to look for.

require(tcltk)
getfile <- function()  {
     name <- tclvalue(tkgetOpenFile(filetypes="{{SPSS Files} {.sav}} {{All files} *}"))
     if (name=="") return;
     zz <- read.spss(name,use.value.label=T,to.data.frame=T)
     assign("myData",zz,envir=.GlobalEnv)
}
tt <- tktoplevel()
button.widget <- tkbutton(tt,text="Select SPSS File",command=getfile)
tkpack(button.widget)


Pressing the button gives the following OpenFile dialog, which knows which file extension to look for. In this case, only files with the extension .sav are displayed. As I don't have SPSS installed on my computer, the .sav file listed below does not have an SPSS icon.



Saving (or opening) Files With More Than One Possible Extension

Multiple possibilities for file extensions (e.g. .jpg and .jpeg) can be separated by a space as follows:

jpegFileName <- tclvalue(tkgetSaveFile(initialfile="foo.jpg",filetypes="{{JPEG Files} {.jpg .jpeg}} {{All files} *}"))