2013-08-16 90 views
0

我學習了Python的Tkinter出頭,和我寫了這個簡單的代碼:的Python的Tkinter - TextBox1中沒有定義

from Tkinter import * 
import tkMessageBox 


def print_it(msg): 
    Text1.insert(INSERT, str(msg)) 

top = Tk() 




Entry1 = Entry(width=300) 
Entry1.pack(side='top') 
Button1 = Button(text='Send',width=300,command=print_it("Message")) 
Button1.pack(side='top') 

Text1 = Text(height=600,width=300) 
Text1.pack(side='top') 



top.geometry('640x480+10+10') 
top.title('GUI') 
top.mainloop() 

我不知道爲什麼,但它給我的錯誤:

NameError: global name 'Text1' is not defined

如果我用Entry1替換print_it def中的Text1,它不會給我任何錯誤。

回答

1

您正在調用print_it,而不是將該函數的引用用作參數command的值。

替換以下行:

Button1 = Button(text='Send',width=300,command=print_it("Message")) 

Button1 = Button(text='Send',width=300,command=lambda: print_it("Message")) 
+0

哦,謝謝,但這不是問題。我需要在聲明Button1小部件之前聲明Text1小部件。 –

+0

@JohnBlack,如果你不替換'command ='部分,按鈕點擊不會觸發'print_it'函數調用。 – falsetru

+0

是的,但主要問題是。不管怎樣,謝謝你。 –