I'm using tkinter. And I am trying to get a file path from a button and use it as an input for an other function. I defined filepathforinfo as a global variable, but I am not getting the expected result.
I tried to follow the solution here.
Here is the main part of the code:
import tkinter.filedialog
import tkinter as tk
def get_pdf_file():
global filepathforinfo #can be avoided by using classes
filetypes=[('PDF files', '*.pdf')]
filepathforinfo = tk.filedialog.askopenfilename( title='Open a file',initialdir='/', filetypes=filetypes)
filepathforinfo='test'
# Toplevel object which will
# be treated as a new window
Information_Window = tk.Tk()
Information_Window.title("Information extraction")
Information_Window.resizable(True, True)
Information_Window['background']='#8c52ff'
info_button = tk.Button(Information_Window, text="Give the pdf file to extract information from", activebackground='purple',activeforeground='purple' ,command=get_pdf_file)
info_button.grid(row=0,column=0)
print(filepathforinfo)
#get_pdf_info(filepathforinfo)
Information_Window.mainloop()
After clicking the button and choosing the file, I get as an output only this :
Out[1]: 'test'
I dont know why I dont get the file path.
The closest answer I got is here, but it is still not satisfying.
filepathforinfovariable's value will only be updated while themainloop()running and the user clicks the button. See explanation of how GUIs work in [my answer}(stackoverflow.com/a/68928369/355230) to a question of which this is essentially a dup,Label— the value offilepathforinfodoes not have to be displayed anywhere. You just need to have this other function you want to pass the value to be invoked by some part of your GUI after theget_pdf_file()function has been run (or maybe as part of it running). Theprint()in your program doesn't work because at that pointget_pdf_file()hasn't run yet — this was the main point I was trying to make by referring you to that other question.