Home > Enterprise >  Tkinter getting file path returned to main function to use and pass on to other functions
Tkinter getting file path returned to main function to use and pass on to other functions

Time:12-31

This is my current code.

from tkinter import *
from tkinter import ttk, filedialog
from tkinter.filedialog import askopenfile
import os

def main():
    path = open_file()
    print(path)
    
# Create an instance of tkinter frame
win = Tk()

# Set the geometry of tkinter frame
win.geometry("700x350")

def open_file():
   
   file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])
   if file:
      filepath = os.path.abspath(file.name)
      quit()
      print(filepath)
    
def quit():
    win.destroy()


# Add a Label widget
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13'))
label.pack(pady=10)

# Create a Button
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)

win.mainloop()

if __name__ == '__main__':
    main()

I want to create a simple GUI to select a file and then use its path in other functions later on. In the current code the filepath prints out fine after the window closes in the open_file function, but it only works if the print statement is in the function. If I remove it from there and want to print it out(just to test) or use it further to pass it to other functions from main it doesn't seem to work. There is no error but it doesn't print anything either. Any idea?

CodePudding user response:

The problem appears to be is wanting to return a value from a function called with a button. This is apparently not possible. The easiest solution I've found (without changing too much of your code structure) is to use a global variable for filepath. Now you can use it pretty much anywhere you want.

Also, I've removed path = open_file() from your main() function as it is redundant. The function is now called only when the button is pressed and not at every start of the program.

from tkinter import * 
from tkinter import ttk, filedialog 
from tkinter.filedialog import askopenfile 
import os

def main():
    print(filepath)
    
# Create an instance of tkinter frame 
win = Tk()

# Set the geometry of tkinter frame 
win.geometry("700x350")

def open_file():
    file = filedialog.askopenfile(mode='r', filetypes=[('PDF', '*.pdf')])    
        if file:
            global filepath
            filepath = os.path.abspath(file.name)
            quit()

def quit():
    win.destroy()


# Add a Label widget 
label = Label(win, text="Click the Button to browse the Files", font=('Georgia 13')) label.pack(pady=10)

# Create a Button 
ttk.Button(win, text="Browse", command=open_file).pack(pady=20)

win.mainloop()

if __name__ == '__main__':
    main()
  • Related