GUI - tkinter Making a button
Question: I want to make a button that will allow the user to browse and select a file
and assign the choice to a variable, this is what I have, I know it is wrong
but I cant seem to get something that works, please give me tips to improve,
thanks.

    
    
    import tkinter
    
    #Window
    window = tkinter.Tk()
    window.title("Title")
    window.geometry("300x400")
    
    #Label
    fileSelectLBL = tkinter.Label(window, text="Please select your file:")
    fileSelectLBL.pack()
    #Button
    filename = tkinter.Button(window, text="Browse", command = askopenfilename( filetypes = (("Text Files","*.txt"))))
    filename.pack()
    
    #Main Loop
    windowindow.mainloop()
    

I get this error when running it:

    
    
        filename = Button(window, text="Browse", command = window.load_file, width = 10)
      File "/usr/lib/python3.4/tkinter/__init__.py", line 1886, in __getattr__
        return getattr(self.tk, attr)
    AttributeError: 'tkapp' object has no attribute 'load_file'
    

And when clicking on the button I get this error:

    
    
    Exception in Tkinter callback
    Traceback (most recent call last):
      File "/usr/lib/python3.4/idlelib/run.py", line 121, in main
        seq, request = rpc.request_queue.get(block=True, timeout=0.05)
      File "/usr/lib/python3.4/queue.py", line 175, in get
        raise Empty
    queue.Empty
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "/usr/lib/python3.4/tkinter/__init__.py", line 1490, in __call__
        return self.func(*args)
    TypeError: load_file() missing 1 required positional argument: 'self'
    

I have updated it to this:

    
    
    import tkinter
    from tkinter import *
    from tkinter.filedialog import askopenfilename
    from tkinter.messagebox import showerror
    from tkinter import filedialog
    #Window
    window = tkinter.Tk()
    window.title("Title")
    window.geometry("300x400")
    def load_file():
        fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("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
    
    
    window.button = Button(window, text="Browse", command=load_file(), width=10)
    
    #Label
    fileSelectLBL = tkinter.Label(window, text="Please select your file:")
    fileSelectLBL.pack()
    
    #Button
    def load_file(self):
        fname = askopenfilename(filetypes=(("Text files", "*.txt"),
                                           ("All files", "*.*") ))
    filename = tkinter.Button(window, text="Browse", command = load_file)
    filename.pack()
    
    filename = Button(window, text="Browse", command = window.load_file, width = 10)
    
    
    #Main Loop
    windowindow.mainloop()
    

Now this opens the file dialog, but it opens as soon as the program is run, I
would like it to only run when the browse button is pressed, what can I do to
fix this?


Answer: You needed to fix your imports, and it's **HIGHLY** recommended to use OOP
with GUIs.

    
    
    from tkinter import *
    from tkinter.filedialog import askopenfilename
    
    class Example(Frame):
        def __init__(self, parent):
            Frame.__init__(self, parent)   
    
            self.parent = parent        
            self.initUI()
    
        def initUI(self):
    
            self.parent.title("File dialog")
    
            #Label
            self.fileSelectLBL = Label(self, text="Please select your file:")
            self.fileSelectLBL.pack()
    
            #Button
            self.filename = Button(self, text="Browse", command = self.load_file)
            self.filename.pack()
    
        def load_file(self, ftypes = None):
            ftypes = ftypes or (("Text Files","*.txt"))
            fl     = askopenfilename(filetypes = ftypes)
    
            if fl != '':
                print(fl)
    
    def main():
        window = Tk()
        ex = Example(window)
        window.geometry("300x400")
    
        #Main Loop
        window.mainloop()
    
    if __name__ == '__main__':
        main() 
    

