5 # tk common file dialogues
7 # this module provides interfaces to the native file dialogues
8 # available in Tk 4.2 and newer, and the directory dialogue available
11 # written by Fredrik Lundh, May 1997.
15 # options (all have default values):
17 # - defaultextension: added to filename if not explicitly given
19 # - filetypes: sequence of (label, pattern) tuples. the same pattern
20 # may occur with several patterns. use "*" as pattern to indicate
23 # - initialdir: initial directory. preserved by dialog instance.
25 # - initialfile: initial file (ignored by the open dialog). preserved
28 # - parent: which window to place the dialog on top of
30 # - title: dialog title
32 # options for the directory chooser:
34 # - initialdir, parent, title: see above
36 # - mustexist: if true, user must pick an existing directory
39 from tkCommonDialog
import Dialog
41 class _Dialog(Dialog
):
43 def _fixoptions(self
):
45 # make sure "filetypes" is a tuple
46 self
.options
["filetypes"] = tuple(self
.options
["filetypes"])
50 def _fixresult(self
, widget
, result
):
52 # keep directory and filename until next time
54 path
, file = os
.path
.split(result
)
55 self
.options
["initialdir"] = path
56 self
.options
["initialfile"] = file
57 self
.filename
= result
# compatibility
65 "Ask for a filename to open"
67 command
= "tk_getOpenFile"
69 class SaveAs(_Dialog
):
70 "Ask for a filename to save as"
72 command
= "tk_getSaveFile"
75 # the directory dialog has its own _fix routines.
76 class Directory(Dialog
):
79 command
= "tk_chooseDirectory"
81 def _fixresult(self
, widget
, result
):
83 # keep directory until next time
84 self
.options
["initialdir"] = result
85 self
.directory
= result
# compatibility
91 def askopenfilename(**options
):
92 "Ask for a filename to open"
94 return Open(**options
).show()
96 def asksaveasfilename(**options
):
97 "Ask for a filename to save as"
99 return SaveAs(**options
).show()
101 # FIXME: are the following two perhaps a bit too convenient?
103 def askopenfile(mode
= "r", **options
):
104 "Ask for a filename to open, and returned the opened file"
106 filename
= Open(**options
).show()
108 return open(filename
, mode
)
111 def asksaveasfile(mode
= "w", **options
):
112 "Ask for a filename to save as, and returned the opened file"
114 filename
= SaveAs(**options
).show()
116 return open(filename
, mode
)
119 def askdirectory (**options
):
120 "Ask for a directory, and return the file name"
121 return Directory(**options
).show()
123 # --------------------------------------------------------------------
126 if __name__
== "__main__":
128 print "open", askopenfilename(filetypes
=[("all filez", "*")])
129 print "saveas", asksaveasfilename()