我的Tkinter项目有问题。我试图创建一个简单的加法计算器,只计算两个数字和。我在创建加法函数时遇到了麻烦。我想创建一个标签来显示变量'finalans',它基本上是用户在输入框Widgets中输入的两位数字之和的值。
def Addition():
top = Toplevel()
top.geometry("500x500")
global finalans
#First Entry
e = Entry(top)
e.pack()
e.focus_set()
#Function for finding answer
def Answer():
firstval = int(e.get())
secondval = int(m.get())
finalans = firstval + secondval
#Final Answer
answer = Label(top, textvariable=finalans)
answer.pack()
h = Label(top, text="First Numeric Value")
h.pack()
#Second Entry
m = Entry(top)
m.pack()
m.focus_set()
z = Label(top, text="Second Numeric Value")
z.pack()
add2 = Button(top, text="Submit", width=10, command=Answer)
add2.pack()
mainloop()
当我尝试运行程序并使用Label小部件显示答案时,标签根本不显示任何内容。控制台甚至没有错误代码或任何东西。如何使Label Widget显示变量?
第一个finalans
必须是StringVar()
。
第二次使用finalans.set(string)
更改
您只能创建一次answer
标签。
def Addition():
top = Toplevel()
top.geometry("500x500")
global finalans
finalans = StringVar()
#First Entry
e = Entry(top)
e.pack()
e.focus_set()
#Function for finding answer
def Answer():
firstval = int(e.get())
secondval = int(m.get())
finalans.set( str(firstval + secondval) )
h = Label(top, text="First Numeric Value")
h.pack()
#Second Entry
m = Entry(top)
m.pack()
m.focus_set()
z = Label(top, text="Second Numeric Value")
z.pack()
add2 = Button(top, text="Submit", width=10, command=Answer)
add2.pack()
#Final Answer
answer = Label(top, textvariable=finalans)
answer.pack()
mainloop()
Addition()