0

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()
1
  • you dont ... or you set a global variable ... typically you would do all your handling in the open_file_handler method, or methods called from that where you pass it as an argument Commented Oct 31, 2013 at 17:43

2 Answers 2

3

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()
Sign up to request clarification or add additional context in comments.

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.