简体   繁体   中英

With Tkinter how to return a value after clicking browse button?

I want to pop up a message at some point and ask to user to choose a file and then display the path of that choosen file. Afterwards, I want to use the path information on the other parts of my project, after the GUI is closed.

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

win = Tk()

win.geometry("400x200")

def open_file():
    file = filedialog.askopenfile(mode='r', filetypes=[('Exe Files', '*.exe')])
    if file:
        filepath = os.path.dirname(file.name)
        Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack()
        return filepath

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

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

win.mainloop()

I want to use the value of the file path after closing the GUI.

EDIT

Apparently I missed what is probably the most salient part of this question:

I want to use the value of the file path after closing the GUI.

In order to accomplish this, you'd have to write the filename out to something like a text file (or any other way of storing it external to your GUI). Then whatever process you're performing which needs that file path can read it from the file.

Another option would be to store the value of filepath in a system environment variable. That way, any process that has access to the environment variables would be able to retrieve the path.


The simplest way to handle this would probably be to globalize the filepath variable. It looks like you have everything else set up the way it needs to be.

filepath = ''  # declare the filepath variable, set to an empty string by default


def open_file():
    global filepath  # let this function modify the value of 'filepath'
   
    # 'file' is a reseved word in Python - it's best not to use it here
    f = filedialog.askopenfile(mode='r', filetypes=[('Exe Files', '*.exe')])
    if f:
        filepath = os.path.dirname(f.name)
        Label(win, text="The File is located at : " + str(filepath), font=('Aerial 11')).pack()
    # no need to return the value as it's now stored in the 'filepath' global

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

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

Bonus Points

If you're using Python 3.8 or later, you can use an assignment expression (aka, the walrus operator := ) to further simplify your if statement

if f := filedialog.askopenfile(mode='r', filetypes=[('Exe Files', '*.exe')])
     print(f)  # or whatever...

Now f is assigned and checked in one line!


Additional FYI

All of the geometry manager methods ( pack , place , and grid ) return None . You're better off declaring your widgets separately from adding them to the window if you intend to refer to them later on

# Avoid this!
my_btn = ttk.Button(win).pack()
print(my_btn)
>>> None
# Do this instead
my_btn = ttk.Button(win)
my_btn.pack()
print(my_btn)
>>> .!button

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM