Question

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?

Was it helpful?

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

OTHER TIPS

Try this:

from Tkinter import *

import tkFileDialog

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

Seems a space name problem. Try this:

try:
    import Tkinter as tk
    import tkFileDialog as fd
except:
    import tkinter as tk
    from tkinter import filedialog as fd

def NewFile():
    print("New File!")
def OpenFile():
    name = fd.askopenfilename()
    print(name)
def About():
    print("This is a simple example of a menu")

class myGUI:
    def __init__(self, root):
        self.root = root

        self.canvas = tk.Canvas(self.root,
                                borderwidth=1,
                                relief="sunken")
        self.canvas.pack( fill=tk.BOTH, expand=tk.YES)

        self.menu = tk.Menu(self.root)
        self.root.config(menu=self.menu)
        self.helpmenu = tk.Menu(self.menu)

        self.filemenu = tk.Menu( self.menu )
        self.menu.add_cascade(label="File", menu=self.filemenu)
        self.filemenu.add_command(label="New", command=NewFile)
        self.filemenu.add_command(label="Open...", command=OpenFile)
        self.filemenu.add_separator()
        self.filemenu.add_command(label="Exit", command=root.destroy)

root = tk.Tk()   
root.title('appName')
myGUI(root)
root.mainloop()    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top