Next / Previous / Contents

55.2. The tkFileDialog module

The tkFileDialog module provides two different pop-up windows you can use to give the user the ability to find existing files or create new files.

.askopenfilename(option=value, ...)

Intended for cases where the user wants to select an existing file. If the user selects a nonexistent file, a popup will appear informing them that the selected file does not exist.

.asksaveasfilename(option=value, ...)

Intended for cases where the user wants to create a new file or replace an existing file. If the user selects an existing file, a pop-up will appear informing that the file already exists, and asking if they really want to replace it.

The arguments to both functions are the same:


The default file extension, a string starting with a period ('.'). If the user's reply contains a period, this argument has no effect. It is appended to the user's reply in case there are no periods.

For example, if you supply a defaultextension='.jpg' argument and the user enters 'gojiro', the returned file name will be 'gojiro.jpg'.

filetypes=[(label1, pattern1), (label2, pattern2), ...]

A list of two-element tuples containing file type names and patterns that will select what appears in the file listing. In the screen picture below, note the pull-down menu labeled “Files of type:”. The filetypes argument you supply will populate this pull-down list. Each pattern is a file type name (“PNG” in the example) and a pattern that selects files of a given type (“(*.png)” in the example).


The path name of the directory to be displayed initially. The default directory is the current working directory.


The file name to be displayed initially in the “File name:” field, if any.


To make the pop-up appear over some window W, supply this argument. The default behavior is that the pop-up will appear over your application's root window.


If specified, T is a string to be displayed as the pop-up window's title.

If the user selects a file, the returned value is the complete path name of the selected file. If the user uses the Cancel button, the function returns an empty string.

Here is an example: