如何存储来自 filedialog.askopenfilename 的数据?

How to store data from filedialog.askopenfilename?

我不知道如何存储 filedialog.askopenfilename 中的值。现在我将该值保存到局部变量,但我想稍后在其他函数中使用该值。我不能 return 这个值,因为我在创建按钮时调用函数。但是我想避免使用全局变量。我怎样才能做到这一点?还有别的办法吗? 这是代码:

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)

下面是一个使用 class 和实例变量的例子:

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