tkinter: get filename of askopenfilename

norseman norseman at hughes.net
Thu Jun 25 19:58:05 CEST 2009


rom wrote:
> 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()
> #####################

Your original, as written, would open and print immediately.  But it 
could be a problem as (or if) more code is added in that area.
This current code allows the user to open, perhaps view via other code 
and print only if wanted.

Either is OK, having both is OK, making it do what Rom wants is best. :)

If open/print was wanted, put the print statement in the open file 
button group right after the open file statement.  Anyone reading the 
code will immediately understand that is the intent. At least for that 
button.

Also it would be best to put the def statements before the button 
statements.  Actually it is best to put all defs BEFORE the GUI (frame, 
buttons, etc...) statements when using Tkinter.

The print filename statement being placed as in the original request may 
attempt to print filename after other code above it is run.  Since 
Tkinter is not a 'closed' package, that is, it's statements can be 
interspersed with program code, it is thus best to make sure what will 
and will not be triggered by other actions.  I've beat my head on that a 
few times. :)


Steve


...(snip)





More information about the Python-list mailing list