blob: e0d5ae5f8b49f664cc04a99e31568f57f0b96356 [file] [log] [blame]
Guido van Rossum1e8c8a21997-07-19 20:02:36 +00001#
2# Instant Python
3# $Id$
4#
5# tk common file dialogues
6#
7# this module provides interfaces to the native file dialogues
8# available in Tk 4.2 and newer.
9#
10# written by Fredrik Lundh, May 1997.
11#
12
13#
14# options (all have default values):
15#
16# - defaultextension: added to filename if not explicitly given
17#
18# - filetypes: sequence of (label, pattern) tuples. the same pattern
19# may occur with several patterns. use "*" as pattern to indicate
20# all files.
21#
22# - initialdir: initial directory. preserved by dialog instance.
23#
24# - initialfile: initial file (ignored by the open dialog). preserved
25# by dialog instance.
26#
27# - parent: which window to place the dialog on top of
28#
29# - title: dialog title
30#
31
32from tkCommonDialog import Dialog
33
34class _Dialog(Dialog):
35
36 def _fixoptions(self):
37 try:
38 # make sure "filetypes" is a tuple
39 self.options["filetypes"] = tuple(self.options["filetypes"])
40 except KeyError:
41 pass
42
43 def _fixresult(self, widget, result):
44 if result:
45 # keep directory and filename until next time
46 import os
47 path, file = os.path.split(result)
48 self.options["initialdir"] = path
49 self.options["initialfile"] = file
50 self.filename = result # compatibility
51 return result
52
53
54#
55# file dialogs
56
57class Open(_Dialog):
58 "Ask for a filename to open"
59
60 command = "tk_getOpenFile"
61
62class SaveAs(_Dialog):
63 "Ask for a filename to save as"
64
65 command = "tk_getSaveFile"
66
67
68#
69# convenience stuff
70
71def askopenfilename(**options):
72 "Ask for a filename to open"
73
74 return apply(Open, (), options).show()
75
76def asksaveasfilename(**options):
77 "Ask for a filename to save as"
78
79 return apply(SaveAs, (), options).show()
80
81# FIXME: are the following two perhaps a bit too convenient?
82
83def askopenfile(mode = "r", **options):
84 "Ask for a filename to open, and returned the opened file"
85
86 filename = apply(Open, (), options).show()
87 if filename:
88 return open(filename, mode)
89 return None
90
91def asksaveasfile(mode = "w", **options):
92 "Ask for a filename to save as, and returned the opened file"
93
94 filename = apply(SaveAs, (), options).show()
95 if filename:
96 return open(filename, mode)
97 return None
98
99
100# --------------------------------------------------------------------
101# test stuff
102
103if __name__ == "__main__":
104
105 print "open", askopenfilename(filetypes=[("all filez", "*")])
106 print "saveas", asksaveasfilename()