简体   繁体   中英

NameError using Tkinter get()

I am creating a drop-down menu using tkinter. It has a submenu "File" and a command "Open" with an entry to allow the user to type the path of the file they want to open and click a button to open it. Currently I'm trying to use get() to retrieve the entry text when the button is clicked, as shown in my code below:

# Assign 5
from tkinter import *

def getFile():
'Displays the text in the entry'
print(E1.get())

def openFile():
'Creates enty widget that allows user file path and open it'
win = Tk()
#add label 
L1 = Label(win, text="File Name")
#display label
L1.pack()
#add entry widget
E1 = Entry(win, bd = 5)
#display entry
E1.pack(fill=X)
#create buttons 
b1 = Button(win, text="Open", width=10, command = getFile)
b2 = Button(win, text = "Cancel", width=10, command=win.quit)
#display the buttons
b1.pack(side = LEFT)
b2.pack(side = LEFT)

# create a blank window 
root = Tk()
root.title("Emmett's awesome window!")

#create a top level menu
menubar = Menu(root)  
# add drop down "File" menu with command "Open" to the menubar
fileMenu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label = "Open", command = openFile)    

# display the menu
root.config(menu=menubar)
root.mainloop()

But I am getting the following error:

Exception in Tkinter callback
Traceback (most recent call last):
File      "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/__init__.py", line 1550, in __call__
return self.func(*args)
File "/Users/emmettgreenberg/Documents/2016/CS521/assign5/assign5_2.py", line  6, in getFile
print(E1.get())
NameError: name 'E1' is not defined

From what I understand, I do not need to pass E1 as an argument when I call getFile . How can I fix this?

Since E1 is a local variable inside openFile() and so it cannot be accessed inside getFile() . Either you make E1 global or pass the content of E1 via getFile() :

def getFile(filename):
    print(filename)

def openFile():
    ...
    b1 = Button(win, text="Open", width=10, command=lambda: getFile(E1.get()))
    ...

Or you can define global StringVar to hold the filename and associate it with E1 :

def getFile():
    print(filename.get())

def openFile():
    ...
    E1 = entry(win, bd=5, textvariable=filename)
    ...

root = Tk()
filename = StringVar()

BTW, better change win = Tk() to win = Toplevel() inside openFile() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM