Assigning tkinter filedialog value to a different variable

Viewed 166

I wish to save the filepath we get from filedialog() in a variable outside the defined function openfile().

Below is the code snippet I am using:

import tkinter as tk
from tkinter import filedialog, Button

root = tk.Tk()

def openfile():
    path = filedialog.askopenfilename()
    return path

Button(root, text = "click to open the stock file", command=openfile).pack(pady=20)

file_path = openfile() # this seems to be causing the issue

The problem is that the filedialog() is getting executed without even getting clicked on.

2 Answers

You're correct about the cause of the filedialog getting executed. Callback functions like openfile() can't return values because it's tkinter that calls them (and it ignores whatever they return). GUI programs require a different programming paradigm than you're probably used to utilized — they're event-driven. This means that they (mostly) only do things as a result of processing user input. For that reason you will need to save the result of calling the askopenfilename() function in a global variable for use later if the value isn't going to be used immediately.

tkinter provides several different kinds of variable classes — BooleanVar, DoubleVar, IntVar, and StringVar — that are good for this sort of thing. In the code below, I show how to use a StringVar to store the path.

The next step will be adding code that does something with the value getting stored in file_path. One possibility would be to add another GUI element, like a Button, that calls another function that does something with the value.

import tkinter as tk
from tkinter import filedialog, Button

root = tk.Tk()
file_path = tk.StringVar()

def openfile():
    path = filedialog.askopenfilename()
    file_path.set(path)  # Save value returned.

Button(root, text="click to open the stock file", command=openfile).pack(pady=20)

root.mainloop()

Here’s what you can do:

def open_file():
    global path
    path = filedialog.askopenfilename()

And then you can access the path variable wherever you want in the program(after the function is ran, obviously.)

Related