2014-11-14 53 views
0

我想從簡單的添加到Python 3.4的輸入框中返回一個答案,但不斷收到以下錯誤。異常在Tkinter回調python在函數中發佈答案,在GUI中的輸入框

Traceback (most recent call last): 
    File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__ 
    return self.func(*args) 
    File "H:\guitest.py", line 12, in calculate 
    enter3.configure(text=answer) 
AttributeError: 'NoneType' object has no attribute 'configure' 


#Imports The Default Graphical Library 
import tkinter 
from tkinter import * 

#Addition Function 
def calculate(): 
    """ take the two numbers entered and process them """ 
    firstnum=int(number1.get()) 

    secondnum=int(number2.get()) 
    answer=firstnum+secondnum 
    enter3.configure(text=answer) 
    return 


#Creates Graphical Window 
window = Tk() 
# Assigns a Name To the Graphical Window 
window.title("MY GUI") 
# Set the Graphical Window Size 
window.geometry("500x200") 

number1=StringVar() 
number2=StringVar() 

label1 = Label(text='1st Number').place(x=50,y=30) 
label2 = Label(text='2nd Number').place(x=150,y=30) 
label3 = Label(text='ANSWER').place(x=100,y=80) 
enter1 =Entry(width=10,textvariable=number1).place(x=50,y=50) 
enter2 =Entry(width=10,textvariable=number2).place(x=150,y=50) 
enter3 =Entry(width=10).place(x=100,y=100) 



#Creates Button 
w = Button(text='ADD',bd=10,command=calculate).place(x=100,y=150) 

#Executes the above Code to Create the Graphical Window 
window.mainloop() 

回答

0

這裏至少有三個問題。

  1. ,都應該被保持UI元素中的變量(例如label1entry3)都沒有,事實上,它們保持。它們設置爲Noneplace方法未返回放置的對象。這只是做配置。所以,你需要你的初始化策略更改爲類似:

    enter3 = Entry(width=10) 
    enter3.place(x=100,y=100) 
    

    如果你認爲,不流暢的風格不太優雅,我會同意...但顯然place不返回的對象,所以你不能做en passant創建和安置。

  2. entry3.configure(text=answer)不會工作,因爲answer不是字符串。這是一個整數。您需要entry3.configure(text=str(answer))。至少。

  3. 我說謊了。這也不會起作用,因爲configure不是如何通常設置Entry小部件文本。請嘗試改爲:

    entry3.delete(0, END) # delete whatever's there already 
    entry3.insert(0, str(answer)) 
    entry3.update() # make sure update is flushed/immediately visible 
    

    請參閱this tutorial更多關於Entry對象。雖然顯式的widget.update()調用可能看起來很笨重,但請相信我 - 當事情沒有按照您認爲應該更新的方式進行更新時,它們會非常方便。

  4. 我不確定你爲什麼使用混合策略。對於輸入,您使用StringVar對象,但隨後您切換到答案窗口小部件的原始更新。並不是說它不會起作用......但是,如果要更新它,只需將number3 = StringVar()設置爲entry3textvariable,然後再將其附加爲number3.set(str(answer))即可。選擇你的毒藥。

即使你做這些改變,你將有一些工作要做,有一個「好」 TK的應用程序,但這些將至少讓更新工作,因爲他們應該,讓你對你的方式。

相關問題