Selecting a file in a directory

rantingrick rantingrick at gmail.com
Sat Feb 13 21:43:20 EST 2010


On Feb 13, 8:00 pm, vsoler <vicente.so... at gmail.com> wrote:
> On Feb 14, 2:45 am, rantingrick <rantingr... at gmail.com> wrote:

(..snip..)

> Excellent!!! Just what I needed!

For your case, since it seems you are writing a "console type"
application you may want to subdue the root window and show the user a
file dialog window *only*. You can do this by using "root.withdraw()"
to hide the root window. Just make sure to destroy the root window
after the users is finished choosing their file (or at some
appropriate time later) or else your program will not exit gracefully
at close time...!

Heres a way to wrap the whole enchilada into a reusable function, of
course many refinements could
be made but this is a simplistic version...

#-- start script --#
# works on python < 3.0
import Tkinter as tk
from tkFileDialog import askopenfilename

def showFileDialog():
    root = tk.Tk()
    root.withdraw()
    path = askopenfilename(filetypes=[('TXT', '.txt')])
    if path:
        print path
        # do something useful here...
    root.destroy()
    root.mainloop()


showFileDialog()
raw_input('press enter to quit...')
#-- end script --#



More information about the Python-list mailing list