How to pass the file location from "askopenfilename" and use it for a second function
This is where classes make things a little easier:
from tkinter import *from tkinter import filedialogimport osclass GUI(): def __init__(self): self.root = Tk() self.filename = "" #root.filename = filedialog.askopenfilename(initialdir="/C") theLabel = Label(self.root, text="The Editor") theLabel.grid(row=0) button1 = Button(self.root, text="Browse", command=self.open) button2 = Button(self.root, text="Run", command=self.other_func) button3 = Button(self.root, text="Quit", command=self.root.quit) button1.grid(row=1) button2.grid(row=2) button3.grid(row=3) self.root.mainloop() def open(self): result = filedialog.askopenfilename(initialdir="C:/") print("Function open read:") print(result) self.filename = result #print("Set class attribute, calling other function") #self.other_func() def other_func(self): with open(self.filename) as f: # 'with' is preferred for it's error handling for c in f: print(c)GUI()
Well you can return the variable:
def open(): result = os.path.dirname(os.path.abspath(__file__)) return resultfile_path = open()
Later you can use file_path
and pass it to a new function.
You could also immediately call that function from inside the open function while passing result
:
def open(): result = os.path.dirname(os.path.abspath(__file__)) your_function(result)
I changed the way you get the file path. I would also advise against naming a function open()
, since it already is a function in itself: