tkFileDialog
If you want to open or save a file or to choose a directory using a filedialog you dont need to implement it on your own. The module tkFileDialog is just for you. In most cases the seven convenience functions provided by the module will serve your needs.
Functions
First you have to decide if you want to open a file or just want to get a filename in order to open the file on your own. In the first case you should use tkFileDialog.askopenfile() in the latter case tkFileDialog.askopenfilename(). Both functions come in a multiple file version with just the same parameters as the single file version which allow the user to select multiple files.
The multiple file versions return a list of open files or a list of file names. If no files were selected or the cancle button was pressed an empty list is returned.
Saving files works in a similar way. You also have two variants of the function, one to get an opened file which you can use to save your data and another to get a file name in order to open the file on your own. These functions are only provided in the single file version. A multiple file version would make no sense.
|
single file |
multiple files |
available options |
open a file |
askopenfile(mode='r', **options) |
askopenfiles(mode='r', **options) |
defaultextension, filetypes, initialdir, initialfile, multiple, message, parent, title |
get a filename to open |
askopenfilename(**options) |
askopenfilenames(**options) |
defaultextension, filetypes, initialdir, initialfile, multiple, message, parent, title |
save a file |
asksaveasfile(mode='w', **options) |
n/a |
defaultextension, filetypes, initialdir, initialfile, multiple, message, parent, title |
get a filename to save |
asksaveasfilename(**options) |
n/a |
defaultextension, filetypes, initialdir, initialfile, multiple, message, parent, title |
choose a directory |
askdirectory(**options) |
n/a |
initialdir, parent, title, mustexist |
Options
-defaultextension extension
- Specifies a string that will be appended to the filename if the user enters a filename without an extension. The default value is the empty string, which means no extension will be appended to the filename in any case. This option is ignored on the Macintosh platform, which does not require extensions to filenames, and the UNIX implementation guesses reasonable values for this from the -filetypes option when this is not supplied.
-filetypes filePatternList
- If a File types listbox exists in the file dialog on the particular platform, this option gives the filetypes in this listbox. When the user choose a filetype in the listbox, only the files of that type are listed. If this option is unspecified, or if it is set to the empty list, or if the File types listbox is not supported by the particular platform then all files are listed regardless of their types. See the section SPECIFYING FILE PATTERNS below for a discussion on the contents of filePatternList.
-initialdir directory
- Specifies that the files in directory should be displayed when the dialog pops up. If this parameter is not specified, then the files in the current working directory are displayed. If the parameter specifies a relative path, the return value will convert the relative path to an absolute path. This option may not always work on the Macintosh. This is not a bug. Rather, the General Controls control panel on the Mac allows the end user to override the application default directory.
-initialfile filename
- Specifies a filename to be displayed in the dialog when it pops up. This option is ignored on the Macintosh platform.
-message string
- Specifies a message to include in the client area of the dialog. This is only available on the Macintosh, and only when Navigation Services are installed.
-multiple boolean
- Allows the user to choose multiple files from the Open dialog. On the Macintosh, this is only available when Navigation Services are installed.
-mustexist boolean
- Specifies whether the user may specify non-existent directories. If this parameter is true, then the user may only select directories that already exist. The default value is false.
-parent window
- Makes window the logical parent of the dialog. The dialog is displayed on top of its parent window.
-title titleString
- Specifies a string to display as the title of the dialog box. If this option is not specified, then a default title will be displayed.
[source:]
Example
This example just should give you an idea of the modules use.
1 import Tkinter, Tkconstants, tkFileDialog
2
3 class TkFileDialogExample(Tkinter.Frame):
4
5 def __init__(self, root):
6
7 Tkinter.Frame.__init__(self, root)
8
9 # options for buttons
10 button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
11
12 # define buttons
13 Tkinter.Button(self, text='askopenfile', command=self.askopenfile).pack(**button_opt)
14 Tkinter.Button(self, text='askopenfilename', command=self.askopenfilename).pack(**button_opt)
15 Tkinter.Button(self, text='asksaveasfile', command=self.asksaveasfile).pack(**button_opt)
16 Tkinter.Button(self, text='asksaveasfilename', command=self.asksaveasfilename).pack(**button_opt)
17 Tkinter.Button(self, text='askdirectory', command=self.askdirectory).pack(**button_opt)
18
19 # define options for opening or saving a file
20 self.file_opt = options = {}
21 options['defaultextension'] = '.txt'
22 options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
23 options['initialdir'] = 'C:\\'
24 options['initialfile'] = 'myfile.txt'
25 options['parent'] = root
26 options['title'] = 'This is a title'
27
28 # This is only available on the Macintosh, and only when Navigation Services are installed.
29 #options['message'] = 'message'
30
31 # if you use the multiple file version of the module functions this option is set automatically.
32 #options['multiple'] = 1
33
34 # defining options for opening a directory
35 self.dir_opt = options = {}
36 options['initialdir'] = 'C:\\'
37 options['mustexist'] = False
38 options['parent'] = root
39 options['title'] = 'This is a title'
40
41 def askopenfile(self):
42
43 """Returns an opened file in read mode."""
44
45 return tkFileDialog.askopenfile(mode='r', **self.file_opt)
46
47 def askopenfilename(self):
48
49 """Returns an opened file in read mode.
50 This time the dialog just returns a filename and the file is opened by your own code.
51 """
52
53 # get filename
54 filename = tkFileDialog.askopenfilename(**self.file_opt)
55
56 # open file on your own
57 if filename:
58 return open(filename, 'r')
59
60 def asksaveasfile(self):
61
62 """Returns an opened file in write mode."""
63
64 return tkFileDialog.asksaveasfile(mode='w', **self.file_opt)
65
66 def asksaveasfilename(self):
67
68 """Returns an opened file in write mode.
69 This time the dialog just returns a filename and the file is opened by your own code.
70 """
71
72 # get filename
73 filename = tkFileDialog.asksaveasfilename(**self.file_opt)
74
75 # open file on your own
76 if filename:
77 return open(filename, 'w')
78
79 def askdirectory(self):
80
81 """Returns a selected directoryname."""
82
83 return tkFileDialog.askdirectory(**self.dir_opt)
84
85 if __name__=='__main__':
86 root = Tkinter.Tk()
87 TkFileDialogExample(root).pack()
88 root.mainloop()
89
Gotchas
References
TODO
Please feel free to modify this article ... english is not my mother tongue!