File Open/Save dialogs in R tcltk

File Open/Save dialogs in R tcltk

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

The Open file dialog

library(tcltk2)
filename <- tclvalue(tkgetOpenFile()) # Very simple, isn't it?
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:

An Open file box

Messagebox

The Save file dialog

filename <- tclvalue(tkgetSaveFile())
if (!nchar(filename)) {
  tkmessageBox(message = "No file was selected!")
} else {
  tkmessageBox(message = paste("The file selected was", filename))
}

With this code, you get the following dialog box:

A Save file box

Now we will assume that the user pressed Cancel:

Messagebox

Opening CSV files with the open file dialog

Here is how you can specify to the OpenFile dialog the type of files to look for:

getcsv <- function() {
  name <- tclvalue(tkgetOpenFile(
    filetypes = "{ {CSV Files} {.csv} } { {All Files} * }"))
  if (name == "")
    return(data.frame()) # Return an empty data frame if no file was selected
  data <- read.csv(name)
  assign("csv_data", data, envir = .GlobalEnv)
  cat("The imported data are in csv_data\n")
}

win1 <- tktoplevel()
win1$env$butSelect <- tk2button(win1, text = "Select CSV File", command = getcsv)
tkpack(win1$env$butSelect)
# The content of the CSV file is placed in the variable 'csv_data' in the global environment

Button to open a file

Pressing the button gives the following OpenFile dialog, which knows which file extension to look for. In this case, only files with the extension .csv are displayed.

Open a csv file box

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:

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

Open Jpeg file box