Access a file from an opening function without calling it

Viewed 57

I want to access a file for later use in Tkinter. The file is selected by the user and opened by a function. The function is called by a button. How do I access this file without calling the function again hence triggering the file selector again.

def select_file():
filetypes = (
    ('Excel files', '*.xlsx'),
)

filename = fd.askopenfilename(
    title='Open file',
    initialdir='/',
    filetypes=filetypes)

showinfo(
    title='Selected File',
    message=filename
)
df = pd.read_excel(filename, engine='openpyxl')

return df


open_button = tk.Button(
    root,
    text='Select File',
    command=select_file
)
open_button.pack()

df = select_file()
print(df.head())

I guess I could maybe make it a global variable within the function? Does not seem very elegant though. I must be missing something obvious. This is, as you might guess my first Tkinter project. Any and all help is appreciated

1 Answers

Tkinter callbacks' return values are not reachable so some options are:

  • global variable
  • a mutable variable, e.g., list and then appending to it
  • binding an attribute to the callback function
  • forming a class on its own
  • ...

Third option:

def select_file():
   # ask for it
   file_name = ...

   # bind to function
   select_file.file_name = file_name

# start with None
select_file.file_name = None

# other things...
# e.g., button placement

# somewhere in the program (possibly in a callback), checking the file name
...f_name = select_file.file_name
...if f_name is not None:
      ...

Another thing to note is that file name is available only after the user is asked, i.e., after the button is pressed. By that time, whole program is traversed and tkinter mainloop is started, so only tkinter events are being listened to. So, you can use the above if in one of those callbacks.

Related