Search code examples
pythonuser-interfacetkinterfiledialog

filedialog to open files within a folder (tkinter)


I have a question about code from this post filedialog, tkinter and opening files

I want to implement this into my own code but when i run this (without my code, just the code you see) all the folders that show up are empty and I can't actually open anything.

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

Solution

  • Your code is running well, i assume what you want to understand is how the filetype is used in the example.

    With the list of types provided (it's a tuple actually) the browse dialog is looking in priority for files with a .tplate extension. Then, you can change this option in the dropdown listbox to select html, python or any type of file.

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

    If you change the order of the tuple provided, you can select another type first,

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

    Check this doc for more details on the options.