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
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.
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.
Then you'll get just the file dialog and nothing else.
The docstring for the withdraw method is:
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