filedialog, tkinter and opening files
The exception you get is telling you filedialog
is not in your namespace.filedialog
(and btw messagebox
) is a tkinter module, so it is not imported just with from tkinter import *
>>> from tkinter import *>>> filedialogTraceback (most recent call last): File "<interactive input>", line 1, in <module>NameError: name 'filedialog' is not defined>>>
you should use for example:
>>> from tkinter import filedialog>>> filedialog<module 'tkinter.filedialog' from 'C:\Python32\lib\tkinter\filedialog.py'>>>>
or
>>> import tkinter.filedialog as fdialog
or
>>> from tkinter.filedialog import askopenfilename
So this would do for your browse button:
from tkinter import *from tkinter.filedialog import askopenfilenamefrom tkinter.messagebox import showerrorclass 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"), ("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) returnif __name__ == "__main__": MyFrame().mainloop()
I had to specify individual commands first and then use the *
to bring all in command.
from tkinter import filedialogfrom tkinter import *
Did you try adding the self prefix to the fileName and replacing the method above the Button ? With the self, it becomes visible between methods.
...def load_file(self): self.fileName = filedialog.askopenfilename(filetypes = (("Template files", "*.tplate") ,("HTML files", "*.html;*.htm") ,("All files", "*.*") ))...