Python 3.x Python在GUI中将答案从函数发布到输入框
在Python3.4中,我试图从简单的添加到输入框中返回一个答案,但不断得到以下错误。Tkinter回调中的异常Python 3.x Python在GUI中将答案从函数发布到输入框,python-3.x,Python 3.x,在Python3.4中,我试图从简单的添加到输入框中返回一个答案,但不断得到以下错误。Tkinter回调中的异常 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.conf
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()
这里至少有三个问题
label1
,entry3
)实际上并不保存它们。它们被设置为None
。place
方法没有返回正在放置的对象。它只是在做定位。因此,您需要将初始化策略更改为:
enter3 = Entry(width=10)
enter3.place(x=100,y=100)
如果您认为非流体样式不太优雅,我会同意……但显然place
不返回对象,因此您无法进行临时创建和放置entry3.configure(text=answer)
不起作用,因为answer
不是字符串。这是一个整数。您需要entry3.configure(text=str(answer))
。至少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
如需有关条目
对象的更多信息,请参阅。虽然显式的widget.update()
调用可能看起来很笨拙,但相信我——当事情没有按您认为的那样更新时,它们会非常方便StringVar
对象,但随后将切换到应答小部件的原始更新。这并不是说它不起作用……但如果您想更新它,只需设置number3=StringVar()
并将其附加为entry3
的textvariable
,然后设置number3.set(str(answer))
可能会更容易。选择你的毒药