I am making a Python GUI where the user types in int values into an Entry widget and then the program adds these values together.

However, for some reason whenever I try to tell the program to add these values it comes up with the error:

TypeError: unsupported operand type(s) for +: 'Entry' and 'Entry'"

I have looked around but can't find anything on this topic. I have tried declaring the Entry widgets as ints and IntVars but it hasn't worked so I'm wondering if it is actually possible to add up Entry values.

有帮助吗?

解决方案

First you must get the string from the Entry and then convert it to an integer.

from Tkinter import *
root = Tk()

e1 = Entry(root)
e2 = Entry(root)
l = Label(root)
def callback():
    total = sum(int(e.get()) for e in (e1, e2))
    l.config(text="answer = %s" % total)
b = Button(root, text="add them", command=callback)
for widget in (e1, e2, l, b):
    widget.pack()
b.mainloop()
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top