blob: e07e5d073924d750d76dddad234ab4fc7ccbe81e [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):
Guido van Rossumc4570481998-03-20 20:45:49 +000044 if result:
45 # keep directory and filename until next time
Guido van Rossum1e8c8a21997-07-19 20:02:36 +000046 import os
Guido van Rossumc4570481998-03-20 20:45:49 +000047 path, file = os.path.split(result)
48 self.options["initialdir"] = path
49 self.options["initialfile"] = file
Guido van Rossum1e8c8a21997-07-19 20:02:36 +000050 self.filename = result # compatibility
Guido van Rossumc4570481998-03-20 20:45:49 +000051 return result
Guido van Rossum1e8c8a21997-07-19 20:02:36 +000052
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()