tkinter: get filename of askopenfilename

rom rompubil at gmail.com
Thu Jun 25 10:02:08 CEST 2009


Thanks again. After your replies, I have understood how to do what I
wanted. What I wanted to do is to get a value after clicking a button
and use it in another part of the program. As you said, after getting
the value, I have to store it in a global variable. However, the
program does not do anything with it until I trigger another event,
e.g. by clicking on another button. Therefore, I have added another
button to my program:
#####################
import Tkinter
import tkFileDialog

filename = 'uninitialized'

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

def print_variable(variable):
    print variable

root = Tkinter.Tk()
Tkinter.Button(root, text='Select file...',
command=open_file_dialog).pack()

Tkinter.Button(root, text='Print file', command=lambda: print_variable
(filename)).pack()

root.mainloop()
#####################

On Jun 25, 4:12 pm, Sean McIlroy <sean_mcil... at yahoo.com> wrote:
> 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