tkinter: get filename of askopenfilename

Sean McIlroy sean_mcilroy at yahoo.com
Thu Jun 25 03:12:22 EDT 2009


i think what he means is to put the global declaration inside the
function that assigns to filename:

def open_file_dialog():
    global filename
    filename = tkFileDialog.askopenfilename(filetypes=
[("allfiles","*")])

as it was, the function was creating a new variable called filename
and assigning to THAT (and then doing absolutely nothing with it).
with the above modification, the function understands that filename
refers to the global variable of that name, and that variable's value
does indeed get printed, but since the print statement comes before
root.mainloop() -- hence before the button gets pressed -- filename
gets printed before the function has assigned to it. this fact becomes
apparent if you initialize the variable with filename='blank' (for
example). putting the print statement after root.mainloop() doesn't
work either, since root.mainloop() keeps control from getting to the
print statement. the effect i think you want can be gotten from
putting the print statement into the function as well, so what you end
up with is this:

import Tkinter
import tkFileDialog

filename = 'uninitialized'

def open_file_dialog():
    global filename
    filename = tkFileDialog.askopenfilename(filetypes=
[("allfiles","*")])
    print filename

root = Tkinter.Tk()
Tkinter.Button(root, text='Notch genes...',
command=open_file_dialog).pack()
root.mainloop()







More information about the Python-list mailing list