Gregory
Gregory

Reputation: 11

How to pass the file location from "askopenfilename" and use it for a second function

It is pretty obvious that I'm pretty new to python and I am trying to make a simple GUI with tkinter that would have two buttons. One "Browse" to open file, and for example "Run" to make some operations with this file.

This is the function that I used for File browser, but how to pass this file location to other functions.

def open():
    result = filedialog.askopenfile(initialdir="/C")
    print(result)

This is the code so far without any special editing.

from tkinter import *
from tkinter import filedialog
import os

root = Tk()

#root.filename = filedialog.askopenfilename(initialdir="/C")


def open():
    result = filedialog.askopenfile(initialdir="/C")
    print(result)
    c=result
    return c


theLabel = Label(root, text="The Editor")
theLabel.grid(row=0)

button1 = Button(root, text="Browse", command=open)
button2 = Button(root, text="Run")
button3 = Button(root, text="Quit", command=root.quit)

button1.grid(row=1)
button2.grid(row=2)
button3.grid(row=3)

root.mainloop()

Upvotes: 1

Views: 1139

Answers (2)

tgikal
tgikal

Reputation: 1680

This is where classes make things a little easier:

from tkinter import *
from tkinter import filedialog
import os

class 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()

Upvotes: 1

EvilTaco
EvilTaco

Reputation: 133

Well you can return the variable:

def open():
    result = os.path.dirname(os.path.abspath(__file__))
    return result

file_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:

https://docs.python.org/3/library/functions.html#open

Upvotes: 0

Related Questions