1 | n/a | """File selection dialog classes. |
---|
2 | n/a | |
---|
3 | n/a | Classes: |
---|
4 | n/a | |
---|
5 | n/a | - FileDialog |
---|
6 | n/a | - LoadFileDialog |
---|
7 | n/a | - SaveFileDialog |
---|
8 | n/a | |
---|
9 | n/a | This module also presents tk common file dialogues, it provides interfaces |
---|
10 | n/a | to the native file dialogues available in Tk 4.2 and newer, and the |
---|
11 | n/a | directory dialogue available in Tk 8.3 and newer. |
---|
12 | n/a | These interfaces were written by Fredrik Lundh, May 1997. |
---|
13 | n/a | """ |
---|
14 | n/a | |
---|
15 | n/a | from tkinter import * |
---|
16 | n/a | from tkinter.dialog import Dialog |
---|
17 | n/a | from tkinter import commondialog |
---|
18 | n/a | |
---|
19 | n/a | import os |
---|
20 | n/a | import fnmatch |
---|
21 | n/a | |
---|
22 | n/a | |
---|
23 | n/a | dialogstates = {} |
---|
24 | n/a | |
---|
25 | n/a | |
---|
26 | n/a | class FileDialog: |
---|
27 | n/a | |
---|
28 | n/a | """Standard file selection dialog -- no checks on selected file. |
---|
29 | n/a | |
---|
30 | n/a | Usage: |
---|
31 | n/a | |
---|
32 | n/a | d = FileDialog(master) |
---|
33 | n/a | fname = d.go(dir_or_file, pattern, default, key) |
---|
34 | n/a | if fname is None: ...canceled... |
---|
35 | n/a | else: ...open file... |
---|
36 | n/a | |
---|
37 | n/a | All arguments to go() are optional. |
---|
38 | n/a | |
---|
39 | n/a | The 'key' argument specifies a key in the global dictionary |
---|
40 | n/a | 'dialogstates', which keeps track of the values for the directory |
---|
41 | n/a | and pattern arguments, overriding the values passed in (it does |
---|
42 | n/a | not keep track of the default argument!). If no key is specified, |
---|
43 | n/a | the dialog keeps no memory of previous state. Note that memory is |
---|
44 | n/a | kept even when the dialog is canceled. (All this emulates the |
---|
45 | n/a | behavior of the Macintosh file selection dialogs.) |
---|
46 | n/a | |
---|
47 | n/a | """ |
---|
48 | n/a | |
---|
49 | n/a | title = "File Selection Dialog" |
---|
50 | n/a | |
---|
51 | n/a | def __init__(self, master, title=None): |
---|
52 | n/a | if title is None: title = self.title |
---|
53 | n/a | self.master = master |
---|
54 | n/a | self.directory = None |
---|
55 | n/a | |
---|
56 | n/a | self.top = Toplevel(master) |
---|
57 | n/a | self.top.title(title) |
---|
58 | n/a | self.top.iconname(title) |
---|
59 | n/a | |
---|
60 | n/a | self.botframe = Frame(self.top) |
---|
61 | n/a | self.botframe.pack(side=BOTTOM, fill=X) |
---|
62 | n/a | |
---|
63 | n/a | self.selection = Entry(self.top) |
---|
64 | n/a | self.selection.pack(side=BOTTOM, fill=X) |
---|
65 | n/a | self.selection.bind('<Return>', self.ok_event) |
---|
66 | n/a | |
---|
67 | n/a | self.filter = Entry(self.top) |
---|
68 | n/a | self.filter.pack(side=TOP, fill=X) |
---|
69 | n/a | self.filter.bind('<Return>', self.filter_command) |
---|
70 | n/a | |
---|
71 | n/a | self.midframe = Frame(self.top) |
---|
72 | n/a | self.midframe.pack(expand=YES, fill=BOTH) |
---|
73 | n/a | |
---|
74 | n/a | self.filesbar = Scrollbar(self.midframe) |
---|
75 | n/a | self.filesbar.pack(side=RIGHT, fill=Y) |
---|
76 | n/a | self.files = Listbox(self.midframe, exportselection=0, |
---|
77 | n/a | yscrollcommand=(self.filesbar, 'set')) |
---|
78 | n/a | self.files.pack(side=RIGHT, expand=YES, fill=BOTH) |
---|
79 | n/a | btags = self.files.bindtags() |
---|
80 | n/a | self.files.bindtags(btags[1:] + btags[:1]) |
---|
81 | n/a | self.files.bind('<ButtonRelease-1>', self.files_select_event) |
---|
82 | n/a | self.files.bind('<Double-ButtonRelease-1>', self.files_double_event) |
---|
83 | n/a | self.filesbar.config(command=(self.files, 'yview')) |
---|
84 | n/a | |
---|
85 | n/a | self.dirsbar = Scrollbar(self.midframe) |
---|
86 | n/a | self.dirsbar.pack(side=LEFT, fill=Y) |
---|
87 | n/a | self.dirs = Listbox(self.midframe, exportselection=0, |
---|
88 | n/a | yscrollcommand=(self.dirsbar, 'set')) |
---|
89 | n/a | self.dirs.pack(side=LEFT, expand=YES, fill=BOTH) |
---|
90 | n/a | self.dirsbar.config(command=(self.dirs, 'yview')) |
---|
91 | n/a | btags = self.dirs.bindtags() |
---|
92 | n/a | self.dirs.bindtags(btags[1:] + btags[:1]) |
---|
93 | n/a | self.dirs.bind('<ButtonRelease-1>', self.dirs_select_event) |
---|
94 | n/a | self.dirs.bind('<Double-ButtonRelease-1>', self.dirs_double_event) |
---|
95 | n/a | |
---|
96 | n/a | self.ok_button = Button(self.botframe, |
---|
97 | n/a | text="OK", |
---|
98 | n/a | command=self.ok_command) |
---|
99 | n/a | self.ok_button.pack(side=LEFT) |
---|
100 | n/a | self.filter_button = Button(self.botframe, |
---|
101 | n/a | text="Filter", |
---|
102 | n/a | command=self.filter_command) |
---|
103 | n/a | self.filter_button.pack(side=LEFT, expand=YES) |
---|
104 | n/a | self.cancel_button = Button(self.botframe, |
---|
105 | n/a | text="Cancel", |
---|
106 | n/a | command=self.cancel_command) |
---|
107 | n/a | self.cancel_button.pack(side=RIGHT) |
---|
108 | n/a | |
---|
109 | n/a | self.top.protocol('WM_DELETE_WINDOW', self.cancel_command) |
---|
110 | n/a | # XXX Are the following okay for a general audience? |
---|
111 | n/a | self.top.bind('<Alt-w>', self.cancel_command) |
---|
112 | n/a | self.top.bind('<Alt-W>', self.cancel_command) |
---|
113 | n/a | |
---|
114 | n/a | def go(self, dir_or_file=os.curdir, pattern="*", default="", key=None): |
---|
115 | n/a | if key and key in dialogstates: |
---|
116 | n/a | self.directory, pattern = dialogstates[key] |
---|
117 | n/a | else: |
---|
118 | n/a | dir_or_file = os.path.expanduser(dir_or_file) |
---|
119 | n/a | if os.path.isdir(dir_or_file): |
---|
120 | n/a | self.directory = dir_or_file |
---|
121 | n/a | else: |
---|
122 | n/a | self.directory, default = os.path.split(dir_or_file) |
---|
123 | n/a | self.set_filter(self.directory, pattern) |
---|
124 | n/a | self.set_selection(default) |
---|
125 | n/a | self.filter_command() |
---|
126 | n/a | self.selection.focus_set() |
---|
127 | n/a | self.top.wait_visibility() # window needs to be visible for the grab |
---|
128 | n/a | self.top.grab_set() |
---|
129 | n/a | self.how = None |
---|
130 | n/a | self.master.mainloop() # Exited by self.quit(how) |
---|
131 | n/a | if key: |
---|
132 | n/a | directory, pattern = self.get_filter() |
---|
133 | n/a | if self.how: |
---|
134 | n/a | directory = os.path.dirname(self.how) |
---|
135 | n/a | dialogstates[key] = directory, pattern |
---|
136 | n/a | self.top.destroy() |
---|
137 | n/a | return self.how |
---|
138 | n/a | |
---|
139 | n/a | def quit(self, how=None): |
---|
140 | n/a | self.how = how |
---|
141 | n/a | self.master.quit() # Exit mainloop() |
---|
142 | n/a | |
---|
143 | n/a | def dirs_double_event(self, event): |
---|
144 | n/a | self.filter_command() |
---|
145 | n/a | |
---|
146 | n/a | def dirs_select_event(self, event): |
---|
147 | n/a | dir, pat = self.get_filter() |
---|
148 | n/a | subdir = self.dirs.get('active') |
---|
149 | n/a | dir = os.path.normpath(os.path.join(self.directory, subdir)) |
---|
150 | n/a | self.set_filter(dir, pat) |
---|
151 | n/a | |
---|
152 | n/a | def files_double_event(self, event): |
---|
153 | n/a | self.ok_command() |
---|
154 | n/a | |
---|
155 | n/a | def files_select_event(self, event): |
---|
156 | n/a | file = self.files.get('active') |
---|
157 | n/a | self.set_selection(file) |
---|
158 | n/a | |
---|
159 | n/a | def ok_event(self, event): |
---|
160 | n/a | self.ok_command() |
---|
161 | n/a | |
---|
162 | n/a | def ok_command(self): |
---|
163 | n/a | self.quit(self.get_selection()) |
---|
164 | n/a | |
---|
165 | n/a | def filter_command(self, event=None): |
---|
166 | n/a | dir, pat = self.get_filter() |
---|
167 | n/a | try: |
---|
168 | n/a | names = os.listdir(dir) |
---|
169 | n/a | except OSError: |
---|
170 | n/a | self.master.bell() |
---|
171 | n/a | return |
---|
172 | n/a | self.directory = dir |
---|
173 | n/a | self.set_filter(dir, pat) |
---|
174 | n/a | names.sort() |
---|
175 | n/a | subdirs = [os.pardir] |
---|
176 | n/a | matchingfiles = [] |
---|
177 | n/a | for name in names: |
---|
178 | n/a | fullname = os.path.join(dir, name) |
---|
179 | n/a | if os.path.isdir(fullname): |
---|
180 | n/a | subdirs.append(name) |
---|
181 | n/a | elif fnmatch.fnmatch(name, pat): |
---|
182 | n/a | matchingfiles.append(name) |
---|
183 | n/a | self.dirs.delete(0, END) |
---|
184 | n/a | for name in subdirs: |
---|
185 | n/a | self.dirs.insert(END, name) |
---|
186 | n/a | self.files.delete(0, END) |
---|
187 | n/a | for name in matchingfiles: |
---|
188 | n/a | self.files.insert(END, name) |
---|
189 | n/a | head, tail = os.path.split(self.get_selection()) |
---|
190 | n/a | if tail == os.curdir: tail = '' |
---|
191 | n/a | self.set_selection(tail) |
---|
192 | n/a | |
---|
193 | n/a | def get_filter(self): |
---|
194 | n/a | filter = self.filter.get() |
---|
195 | n/a | filter = os.path.expanduser(filter) |
---|
196 | n/a | if filter[-1:] == os.sep or os.path.isdir(filter): |
---|
197 | n/a | filter = os.path.join(filter, "*") |
---|
198 | n/a | return os.path.split(filter) |
---|
199 | n/a | |
---|
200 | n/a | def get_selection(self): |
---|
201 | n/a | file = self.selection.get() |
---|
202 | n/a | file = os.path.expanduser(file) |
---|
203 | n/a | return file |
---|
204 | n/a | |
---|
205 | n/a | def cancel_command(self, event=None): |
---|
206 | n/a | self.quit() |
---|
207 | n/a | |
---|
208 | n/a | def set_filter(self, dir, pat): |
---|
209 | n/a | if not os.path.isabs(dir): |
---|
210 | n/a | try: |
---|
211 | n/a | pwd = os.getcwd() |
---|
212 | n/a | except OSError: |
---|
213 | n/a | pwd = None |
---|
214 | n/a | if pwd: |
---|
215 | n/a | dir = os.path.join(pwd, dir) |
---|
216 | n/a | dir = os.path.normpath(dir) |
---|
217 | n/a | self.filter.delete(0, END) |
---|
218 | n/a | self.filter.insert(END, os.path.join(dir or os.curdir, pat or "*")) |
---|
219 | n/a | |
---|
220 | n/a | def set_selection(self, file): |
---|
221 | n/a | self.selection.delete(0, END) |
---|
222 | n/a | self.selection.insert(END, os.path.join(self.directory, file)) |
---|
223 | n/a | |
---|
224 | n/a | |
---|
225 | n/a | class LoadFileDialog(FileDialog): |
---|
226 | n/a | |
---|
227 | n/a | """File selection dialog which checks that the file exists.""" |
---|
228 | n/a | |
---|
229 | n/a | title = "Load File Selection Dialog" |
---|
230 | n/a | |
---|
231 | n/a | def ok_command(self): |
---|
232 | n/a | file = self.get_selection() |
---|
233 | n/a | if not os.path.isfile(file): |
---|
234 | n/a | self.master.bell() |
---|
235 | n/a | else: |
---|
236 | n/a | self.quit(file) |
---|
237 | n/a | |
---|
238 | n/a | |
---|
239 | n/a | class SaveFileDialog(FileDialog): |
---|
240 | n/a | |
---|
241 | n/a | """File selection dialog which checks that the file may be created.""" |
---|
242 | n/a | |
---|
243 | n/a | title = "Save File Selection Dialog" |
---|
244 | n/a | |
---|
245 | n/a | def ok_command(self): |
---|
246 | n/a | file = self.get_selection() |
---|
247 | n/a | if os.path.exists(file): |
---|
248 | n/a | if os.path.isdir(file): |
---|
249 | n/a | self.master.bell() |
---|
250 | n/a | return |
---|
251 | n/a | d = Dialog(self.top, |
---|
252 | n/a | title="Overwrite Existing File Question", |
---|
253 | n/a | text="Overwrite existing file %r?" % (file,), |
---|
254 | n/a | bitmap='questhead', |
---|
255 | n/a | default=1, |
---|
256 | n/a | strings=("Yes", "Cancel")) |
---|
257 | n/a | if d.num != 0: |
---|
258 | n/a | return |
---|
259 | n/a | else: |
---|
260 | n/a | head, tail = os.path.split(file) |
---|
261 | n/a | if not os.path.isdir(head): |
---|
262 | n/a | self.master.bell() |
---|
263 | n/a | return |
---|
264 | n/a | self.quit(file) |
---|
265 | n/a | |
---|
266 | n/a | |
---|
267 | n/a | |
---|
268 | n/a | # For the following classes and modules: |
---|
269 | n/a | # |
---|
270 | n/a | # options (all have default values): |
---|
271 | n/a | # |
---|
272 | n/a | # - defaultextension: added to filename if not explicitly given |
---|
273 | n/a | # |
---|
274 | n/a | # - filetypes: sequence of (label, pattern) tuples. the same pattern |
---|
275 | n/a | # may occur with several patterns. use "*" as pattern to indicate |
---|
276 | n/a | # all files. |
---|
277 | n/a | # |
---|
278 | n/a | # - initialdir: initial directory. preserved by dialog instance. |
---|
279 | n/a | # |
---|
280 | n/a | # - initialfile: initial file (ignored by the open dialog). preserved |
---|
281 | n/a | # by dialog instance. |
---|
282 | n/a | # |
---|
283 | n/a | # - parent: which window to place the dialog on top of |
---|
284 | n/a | # |
---|
285 | n/a | # - title: dialog title |
---|
286 | n/a | # |
---|
287 | n/a | # - multiple: if true user may select more than one file |
---|
288 | n/a | # |
---|
289 | n/a | # options for the directory chooser: |
---|
290 | n/a | # |
---|
291 | n/a | # - initialdir, parent, title: see above |
---|
292 | n/a | # |
---|
293 | n/a | # - mustexist: if true, user must pick an existing directory |
---|
294 | n/a | # |
---|
295 | n/a | |
---|
296 | n/a | |
---|
297 | n/a | class _Dialog(commondialog.Dialog): |
---|
298 | n/a | |
---|
299 | n/a | def _fixoptions(self): |
---|
300 | n/a | try: |
---|
301 | n/a | # make sure "filetypes" is a tuple |
---|
302 | n/a | self.options["filetypes"] = tuple(self.options["filetypes"]) |
---|
303 | n/a | except KeyError: |
---|
304 | n/a | pass |
---|
305 | n/a | |
---|
306 | n/a | def _fixresult(self, widget, result): |
---|
307 | n/a | if result: |
---|
308 | n/a | # keep directory and filename until next time |
---|
309 | n/a | # convert Tcl path objects to strings |
---|
310 | n/a | try: |
---|
311 | n/a | result = result.string |
---|
312 | n/a | except AttributeError: |
---|
313 | n/a | # it already is a string |
---|
314 | n/a | pass |
---|
315 | n/a | path, file = os.path.split(result) |
---|
316 | n/a | self.options["initialdir"] = path |
---|
317 | n/a | self.options["initialfile"] = file |
---|
318 | n/a | self.filename = result # compatibility |
---|
319 | n/a | return result |
---|
320 | n/a | |
---|
321 | n/a | |
---|
322 | n/a | # |
---|
323 | n/a | # file dialogs |
---|
324 | n/a | |
---|
325 | n/a | class Open(_Dialog): |
---|
326 | n/a | "Ask for a filename to open" |
---|
327 | n/a | |
---|
328 | n/a | command = "tk_getOpenFile" |
---|
329 | n/a | |
---|
330 | n/a | def _fixresult(self, widget, result): |
---|
331 | n/a | if isinstance(result, tuple): |
---|
332 | n/a | # multiple results: |
---|
333 | n/a | result = tuple([getattr(r, "string", r) for r in result]) |
---|
334 | n/a | if result: |
---|
335 | n/a | path, file = os.path.split(result[0]) |
---|
336 | n/a | self.options["initialdir"] = path |
---|
337 | n/a | # don't set initialfile or filename, as we have multiple of these |
---|
338 | n/a | return result |
---|
339 | n/a | if not widget.tk.wantobjects() and "multiple" in self.options: |
---|
340 | n/a | # Need to split result explicitly |
---|
341 | n/a | return self._fixresult(widget, widget.tk.splitlist(result)) |
---|
342 | n/a | return _Dialog._fixresult(self, widget, result) |
---|
343 | n/a | |
---|
344 | n/a | class SaveAs(_Dialog): |
---|
345 | n/a | "Ask for a filename to save as" |
---|
346 | n/a | |
---|
347 | n/a | command = "tk_getSaveFile" |
---|
348 | n/a | |
---|
349 | n/a | |
---|
350 | n/a | # the directory dialog has its own _fix routines. |
---|
351 | n/a | class Directory(commondialog.Dialog): |
---|
352 | n/a | "Ask for a directory" |
---|
353 | n/a | |
---|
354 | n/a | command = "tk_chooseDirectory" |
---|
355 | n/a | |
---|
356 | n/a | def _fixresult(self, widget, result): |
---|
357 | n/a | if result: |
---|
358 | n/a | # convert Tcl path objects to strings |
---|
359 | n/a | try: |
---|
360 | n/a | result = result.string |
---|
361 | n/a | except AttributeError: |
---|
362 | n/a | # it already is a string |
---|
363 | n/a | pass |
---|
364 | n/a | # keep directory until next time |
---|
365 | n/a | self.options["initialdir"] = result |
---|
366 | n/a | self.directory = result # compatibility |
---|
367 | n/a | return result |
---|
368 | n/a | |
---|
369 | n/a | # |
---|
370 | n/a | # convenience stuff |
---|
371 | n/a | |
---|
372 | n/a | def askopenfilename(**options): |
---|
373 | n/a | "Ask for a filename to open" |
---|
374 | n/a | |
---|
375 | n/a | return Open(**options).show() |
---|
376 | n/a | |
---|
377 | n/a | def asksaveasfilename(**options): |
---|
378 | n/a | "Ask for a filename to save as" |
---|
379 | n/a | |
---|
380 | n/a | return SaveAs(**options).show() |
---|
381 | n/a | |
---|
382 | n/a | def askopenfilenames(**options): |
---|
383 | n/a | """Ask for multiple filenames to open |
---|
384 | n/a | |
---|
385 | n/a | Returns a list of filenames or empty list if |
---|
386 | n/a | cancel button selected |
---|
387 | n/a | """ |
---|
388 | n/a | options["multiple"]=1 |
---|
389 | n/a | return Open(**options).show() |
---|
390 | n/a | |
---|
391 | n/a | # FIXME: are the following perhaps a bit too convenient? |
---|
392 | n/a | |
---|
393 | n/a | def askopenfile(mode = "r", **options): |
---|
394 | n/a | "Ask for a filename to open, and returned the opened file" |
---|
395 | n/a | |
---|
396 | n/a | filename = Open(**options).show() |
---|
397 | n/a | if filename: |
---|
398 | n/a | return open(filename, mode) |
---|
399 | n/a | return None |
---|
400 | n/a | |
---|
401 | n/a | def askopenfiles(mode = "r", **options): |
---|
402 | n/a | """Ask for multiple filenames and return the open file |
---|
403 | n/a | objects |
---|
404 | n/a | |
---|
405 | n/a | returns a list of open file objects or an empty list if |
---|
406 | n/a | cancel selected |
---|
407 | n/a | """ |
---|
408 | n/a | |
---|
409 | n/a | files = askopenfilenames(**options) |
---|
410 | n/a | if files: |
---|
411 | n/a | ofiles=[] |
---|
412 | n/a | for filename in files: |
---|
413 | n/a | ofiles.append(open(filename, mode)) |
---|
414 | n/a | files=ofiles |
---|
415 | n/a | return files |
---|
416 | n/a | |
---|
417 | n/a | |
---|
418 | n/a | def asksaveasfile(mode = "w", **options): |
---|
419 | n/a | "Ask for a filename to save as, and returned the opened file" |
---|
420 | n/a | |
---|
421 | n/a | filename = SaveAs(**options).show() |
---|
422 | n/a | if filename: |
---|
423 | n/a | return open(filename, mode) |
---|
424 | n/a | return None |
---|
425 | n/a | |
---|
426 | n/a | def askdirectory (**options): |
---|
427 | n/a | "Ask for a directory, and return the file name" |
---|
428 | n/a | return Directory(**options).show() |
---|
429 | n/a | |
---|
430 | n/a | |
---|
431 | n/a | |
---|
432 | n/a | # -------------------------------------------------------------------- |
---|
433 | n/a | # test stuff |
---|
434 | n/a | |
---|
435 | n/a | def test(): |
---|
436 | n/a | """Simple test program.""" |
---|
437 | n/a | root = Tk() |
---|
438 | n/a | root.withdraw() |
---|
439 | n/a | fd = LoadFileDialog(root) |
---|
440 | n/a | loadfile = fd.go(key="test") |
---|
441 | n/a | fd = SaveFileDialog(root) |
---|
442 | n/a | savefile = fd.go(key="test") |
---|
443 | n/a | print(loadfile, savefile) |
---|
444 | n/a | |
---|
445 | n/a | # Since the file name may contain non-ASCII characters, we need |
---|
446 | n/a | # to find an encoding that likely supports the file name, and |
---|
447 | n/a | # displays correctly on the terminal. |
---|
448 | n/a | |
---|
449 | n/a | # Start off with UTF-8 |
---|
450 | n/a | enc = "utf-8" |
---|
451 | n/a | import sys |
---|
452 | n/a | |
---|
453 | n/a | # See whether CODESET is defined |
---|
454 | n/a | try: |
---|
455 | n/a | import locale |
---|
456 | n/a | locale.setlocale(locale.LC_ALL,'') |
---|
457 | n/a | enc = locale.nl_langinfo(locale.CODESET) |
---|
458 | n/a | except (ImportError, AttributeError): |
---|
459 | n/a | pass |
---|
460 | n/a | |
---|
461 | n/a | # dialog for openening files |
---|
462 | n/a | |
---|
463 | n/a | openfilename=askopenfilename(filetypes=[("all files", "*")]) |
---|
464 | n/a | try: |
---|
465 | n/a | fp=open(openfilename,"r") |
---|
466 | n/a | fp.close() |
---|
467 | n/a | except: |
---|
468 | n/a | print("Could not open File: ") |
---|
469 | n/a | print(sys.exc_info()[1]) |
---|
470 | n/a | |
---|
471 | n/a | print("open", openfilename.encode(enc)) |
---|
472 | n/a | |
---|
473 | n/a | # dialog for saving files |
---|
474 | n/a | |
---|
475 | n/a | saveasfilename=asksaveasfilename() |
---|
476 | n/a | print("saveas", saveasfilename.encode(enc)) |
---|
477 | n/a | |
---|
478 | n/a | if __name__ == '__main__': |
---|
479 | n/a | test() |
---|