2016-11-15 30 views
0

我使用tkinter創建了一個下拉菜單。它有一個子菜單「文件」和一個命令「打開」,其中有一個條目允許用戶輸入他們想要打開的文件的路徑,然後點擊一個按鈕打開它。目前我正在嘗試使用get()來檢索項文本時,單擊該按鈕時,如下圖所示我的代碼:使用Tkinter的NameError get()

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

但我收到以下錯誤:

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 

據我所知,當我撥打getFile時,我不需要通過E1作爲參數。我怎樣才能解決這個問題?

回答

1

由於E1openFile()之內的局部變量,因此無法在getFile()之內進行訪問。要麼你讓E1全球或通過getFile()合格E1內容:

def getFile(filename): 
    print(filename) 

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

或者你可以定義全局StringVarE1持有的文件名和關聯的:

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

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

root = Tk() 
filename = StringVar() 

BTW,最好換win = Tk()win = Toplevel()裏面openFile()

+0

謝謝,我用lambda來傳遞文件名,它的工作原理,但我不明白,爲什麼lambda需要?此外,爲什麼使用** Toplevel()**而不是** Tk()**? –

+0

@EmmettGreenberg通常,一個tkinter應用程序應該有一個Tk主應用程序小部件。多於一個會導致微妙的錯誤。 –

+0

lambda用於將'openFile()'函數範圍內定義的任何資源傳遞給'getFile()'函數。使用'TK()'將初始化root'窗口的'另一個實例,其獨立於所述第一創建'root'窗口,但'的Toplevel()'將是第一個'root'窗口的分層結構內。似乎兩者都可以達到同樣的效果,但背後的含義是不同的。 – acw1668

相關問題