我在Tkinter项目中遇到问题。我正在尝试创建一个简单的加法计算器,只计算两个数字和。我在创建添加功能时遇到问题。我想创建一个标签,显示变量' finalans'这基本上是用户在Entry Box 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显示变量?
答案 0 :(得分:1)
首先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()