ยปCore Development>Code coverage>Lib/tkinter/filedialog.py

Python code coverage for Lib/tkinter/filedialog.py

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