Search code examples
pythontkinterbuttontk-toolkitfiledialog

How to store data from filedialog.askopenfilename?


I cant figure out how to store value from filedialog.askopenfilename. Now i saved the value to local variable but i want to work with this value later in other functions. I cant return the this value because i call function when i am creating the button. However i want to avoid using global variable. How can i do this? Is there some other way? Here is code:

from tkinter import Tk, StringVar, ttk
from tkinter import filedialog
from tkinter import messagebox
def browse_files():
    filename = filedialog.askopenfilename(initialdir = "/",
                                          title = "Select a File",
                                          filetypes = (("Text files",
                                                        "*.txt*"),
                                                       ("all files",
                                                        "*.*")))
    print(filename)
root = Tk()
button1 = ttk.Button(root,text='Browse', command=browse_files)
button1.grid(row=0,column=0)

Solution

  • Below is an example using class and instance variable:

    from tkinter import Tk, ttk
    from tkinter import filedialog
    
    class App(Tk):
        def __init__(self):
            super().__init__()
            self.filename = None
    
            button1 = ttk.Button(self, text='Browse', command=self.browse_files)
            button1.grid(row=0, column=0)
    
            button2 = ttk.Button(self, text='Show', command=self.show)
            button2.grid(row=0, column=1)
    
        def browse_files(self):
            # use instance variable self.filename
            self.filename = filedialog.askopenfilename(initialdir="/",
                                                       title="Select a File",
                                                       filetypes=(("Text files", "*.txt*"),
                                                                  ("all files", "*.*")))
    
        def show(self):
            print(self.filename)
    
    root = App()
    root.mainloop()