Tk
There are Tk commands that bring up the standard Windows style file browsers for selecting directories and files to open or save.
The following table contains some commonly used Tk file commands and a summary of their
usage. For more in-depth explanations and a complete listing, referred to
http://www.tcl.tk/man/ or to a Tcl/Tk handbook.
- tk_getOpenFile
- Opens a file browser to allow you to select an existing file.
- tk_getSaveFile
- Opens a file browser to allow you to either enter a new file name or select an existing file. If the file exists, you are prompted to overwrite the file.
- tk_chooseDirectory
- Opens a file browser to allow you to either enter a new directory name or select an existing directory.
There are additional options to these commands that allow for multiple file selection, initial directory specifications and file filtering, among others.
To open a file for reading, use
tk_getOpenFile.
set filename [tk_getOpenFile];
puts "$filename";
Tcl returns the selected file name.
To select a file for saving, use tk_getSaveFile. The
tk_getSaveFile command handles everything for you including write
permissions, selecting existing files, creating directories on the fly, and all other
functionality included in standard file browser. tk_getSaveFile returns
the selected filename but does not actually create a
file.
set filename [tk_getSaveFile];
puts "$filename";
Tcl returns the selected file name.
To make file selections easier for the user, the tk_getOpenFile and
tk_getSaveFile commands provide a -filetypes option.
This option takes only one parameter which is a list of file types. Each file type is also a
list containing two parameters which are a file type description and the file extension.
Since spaces are treated as list separators, parameters that contain spaces must be
contained within quotes or braces. A file types parameter might look
like:
{{"File Description 1" *.ext1} {"File Description 2" *.ext2}};
set filetypes "{{OptiStruct files} {*.fem *.parm}} {{All Files} {*.*}}";
set filename [tk_getOpenFile -filetypes $filetypes];
puts $filename;
Tcl returns the selected file name.
Now that you have a full path to a file, you will probably need to find out the file name
without the full path, which directory the file is located in, and the file extension. If
you selected a file named C:/My_files/readme.txt from the
tk_getOpenFile
command:
set filename [tk_getOpenFile];
C:/My_files/readme.txt
file dirname $filename;
C:/My_files
file tail $filename;
readme.txt
file extension $filename;
.txt
file rootname $filename;
readme
set path_list [file split $filename];
C:/ My_files readme.txt
lindex $path_list end;
readme.txt