Access a file from an opening function without calling it Access a file from an opening function without calling it tkinter tkinter

Access a file from an opening function without calling it


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 Noneselect_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.