filedialog 打开文件夹中的文件 (tkinter)

filedialog to open files within a folder (tkinter)

我对这个 post 中的代码有疑问 filedialog, tkinter and opening files

我想将它实现到我自己的代码中,但是当我 运行 这个(没有我的代码,只有你看到的代码)时,显示的所有文件夹都是空的,我实际上无法打开任何东西.

from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror

class MyFrame(Frame):
    def __init__(self):
        Frame.__init__(self)
        self.master.title("Example")
        self.master.rowconfigure(5, weight=1)
        self.master.columnconfigure(5, weight=1)
        self.grid(sticky=W+E+N+S)

        self.button = Button(self, text="Browse", command=self.load_file, width=10)
        self.button.grid(row=1, column=0, sticky=W)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("Python file", "*.py"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                print("""here it comes: self.settings["template"].set(fname)""")
            except:                     # <- naked except is a bad idea
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return


if __name__ == "__main__":
    MyFrame().mainloop()

您的代码是 运行 好吧,我假设您想了解的是示例中文件类型的使用方式。

通过提供的类型列表(实际上是一个元组),浏览对话框优先查找扩展名为 .tplate 的文件。 然后,您可以在下拉列表框中将此选项更改为 select html、python 或任何类型的文件。

fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                   ("HTML files", "*.html;*.htm"),
                                   ("Python file", "*.py"),
                                   ("All files", "*.*") ))

如果您更改提供的元组的顺序,您可以select先使用另一种类型,

fname = askopenfilename(filetypes=(("Python file", "*.py"),
                                   ("HTML files", "*.html;*.htm"),
                                   ("All files", "*.*") ))

检查此 doc 以获取有关选项的更多详细信息。