pythonpython-2.7tkinterfile-browser

NameError: name 'tkFileDialog' is not defined


I'm trying to use Tkinter and get the user to choose a certain file. My code looks like this (I'm just starting out with Tkinter)

from Tkinter import *
from tkFileDialog import *


root = Tk()

root.wm_title("Pages to PDF")
root.wm_iconbitmap('icon.ico')
w = Label(root, text="Please choose a .pages file to convert.") 
y = tkFileDialog.askopenfilename(parent=root)
y.pack()
w.pack()

root.mainloop()

When I run the program, I get an error that says:

NameError: name 'tkFileDialog' is not defined

I've tried it with a few configurations I found online. None of them have worked; but this is the same basic error every time. How can I fix this?


Solution

  • You are importing everything from tkFileDialog module, so you don't need to write a module-name prefixed tkFileDialog.askopenfilename(), just askopenfilename(), like:

    from Tkinter import *
    from tkFileDialog import *
    root = Tk()
    root.wm_title("Pages to PDF")
    
    w = Label(root, text="Please choose a .pages file to convert.") 
    fileName = askopenfilename(parent=root)
    
    w.pack()
    root.mainloop()