Reputation: 3
Im trying to use tkinter to open a file dialog, once this file dialogue is open how do i get the file object that is returned by the function. As in how do i access it in main?
basically how do i handle return values by functions that are invoked by command
import sys
import Tkinter
from tkFileDialog import askopenfilename
#import tkMessageBox
def quit_handler():
print "program is quitting!"
sys.exit(0)
def open_file_handler():
file= askopenfilename()
print file
return file
main_window = Tkinter.Tk()
open_file = Tkinter.Button(main_window, command=open_file_handler, padx=100, text="OPEN FILE")
open_file.pack()
quit_button = Tkinter.Button(main_window, command=quit_handler, padx=100, text="QUIT")
quit_button.pack()
main_window.mainloop()
Upvotes: 0
Views: 6790
Reputation: 20178
the easiest way I can think of is to make a StringVar
file_var = Tkinter.StringVar(main_window, name='file_var')
change your callback command using lambda
to pass the StringVar
to your callback
command = lambda: open_file_handler(file_var)
then in your callback, set the StringVar
to file
def open_file_handler(file_var):
file_name = askopenfilename()
print file_name
#return file_name
file_var.set(file_name)
Then in your button use command
instead of open_file_handler
open_file = Tkinter.Button(main_window, command=command,
padx=100, text="OPEN FILE")
open_file.pack()
Then you can retrieve the file using
file_name = file_var.get()
Upvotes: 1
Reputation: 17532
Instead of returning the file
variable, just handle it there (I also renamed the file
variable so you do not override the built-in class):
def open_file_handler():
filePath= askopenfilename() # don't override the built-in file class
print filePath
# do whatever with the file here
Alternatively, you can simply link the button to another function, and handle it there:
def open_file_handler():
filePath = askopenfilename()
print filePath
return filePath
def handle_file():
filePath = open_file_handler()
# handle the file
Then, in the button:
open_file = Tkinter.Button(main_window, command=handle_file, padx=100, text="OPEN FILE")
open_file.pack()
Upvotes: 3