ActiveState Code

Recipe 438123: File Tkinter dialogs


Basic Tkinter dialogs for directory selection, file selection and so on. That's dirt simple (although the official documentation is not very explicit about these features).

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# ======== Select a directory:

import Tkinter, tkFileDialog

root = Tkinter.Tk()
dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Please select a directory')
if len(dirname ) > 0:
    print "You chose %s" % dirname 


# ======== Select a file for opening:
import Tkinter,tkFileDialog

root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
if file != None:
    data = file.read()
    file.close()
    print "I got %d bytes from this file." % len(data)


# ======== "Save as" dialog:
import Tkinter,tkFileDialog

myFormats = [
    ('Windows Bitmap','*.bmp'),
    ('Portable Network Graphics','*.png'),
    ('JPEG / JFIF','*.jpg'),
    ('CompuServer GIF','*.gif'),
    ]

root = Tkinter.Tk()
fileName = tkFileDialog.asksaveasfilename(parent=root,filetypes=myFormats ,title="Save the image as...")
if len(fileName ) > 0:
    print "Now saving under %s" % nomFichier

Discussion

Tkinter is provided with many standard file/directory dialogs. They are very handy, and very easy to use. I wrote these samples because I had some problem finding proper examples for this.

Comments

  1. 1. At 7:08 a.m. on 26 jul 2005, Michael Foord said:

    Pretty Good. If you think there is missing stuff in the standard library documentation then send your examples to the documetnation maintainers - who are always looking for more material.

  2. 2. At 1:14 p.m. on 9 feb 2006, Jason Drew said:

    Same again, but without the main app window in the background. Nice reminder of these handy little functions. One improvement (for me anyway) is to remove the empty application window that pops up behind the file dialogs. If your program only needs the file dialogs and no other application window, that empty window is a distraction. The solution is to use the window manager's withdraw() method. E.g.

    >>> import Tkinter, tkFileDialog
    >>> root = Tkinter.Tk()
    >>> root.withdraw()
    ''
    >>> dirname = tkFileDialog.askdirectory(parent=root,initialdir="/",title='Pick a directory')
    

    Then you'll get just the file dialog and nothing else.

    The docstring for the withdraw method is:

    >>> print Tkinter.Tk.withdraw.__doc__
    Withdraw this widget from the screen such that it is unmapped and forgotten by the window manager. Re-draw it with wm_deiconify.
    
  3. 3. At 3:58 a.m. on 24 mar 2007, James Stroud said:

    Good Recipe. As I've used this for every example today, good job! And I know Tkinter pretty well. Its good to have boilerplate like this come up easily via google.

Sign in to comment