Reputation: 73
I'm trying to make a GUI with Tkinter where you type two numbers in and it adds them together. I'm unsure how to display the answer in my window. Also when I run it there is an error which says: TypeError: unsupported operand type(s) for +: 'Entry' and 'Entry'
from tkinter import *
window = Tk()
def add():
label = Label(window, text=entry1 + entry2)
entry1 = Entry(window, width=10)
entry2 = Entry(window, width=10)
button = Button(window, text='Click to add', command=add)
entry1.pack()
entry2.pack()
button.pack()
label.pack()
If someone could help me fix my code I would greatly appreciate it.
Upvotes: 0
Views: 294
Reputation: 462
Your code had few mistakes. First one is that you can not add two entries just by placing a "+" symbol in between them. You need to get the values which are STRING, then convert it into INTEGER, ADD them and then set the value of the ENTRY BOX to it. Second mistake is that you are not using the MAIN LOOP. Without MAIN LOOP the tkinter GUI will disappear, so to keep the GUI use LOOP.
Using notepad++. Tested on windows 7. Python 2.7
from tkinter import *
window = Tk()
#name window
window.title('My Add')
#window sized
window.geometry('250x200')
def add():
sum = int(entry1.get()) + int(entry2.get())
entry3.delete(0,END)
entry3.insert(0,str(sum))
L1 = Label(window, text='Number 1:')
entry1 = Entry(window, width=20)
L1.pack()
entry1.pack()
L2 = Label(window, text='Number 2:')
entry2 = Entry(window, width=20)
L2.pack()
entry2.pack()
button = Button(window, text='Click to add', command=add)
button.pack()
L3 = Label(window, text='Sum of Number 1 and Number 2:')
entry3 = Entry(window, width=20)
L3.pack()
entry3.pack()
window.mainloop()
Upvotes: 1
Reputation: 2418
Your code contains a number of mistakes. You cannot directly use the Entry field, instead you need to add the values in the Entry field. You also need to add the main loop processing of tkinter.
Following is a quick running example without any error handling (It fails if you don't enter values for one of the Entry fields),
import tkinter
mainWindow = tkinter.Tk()
mainWindow.title("Demo App")
mainWindow.geometry("640x480+200+200")
entry1 = tkinter.Entry(mainWindow,width=10)
entry2 = tkinter.Entry(mainWindow,width=10)
entry1.pack()
entry2.pack()
label = tkinter.Label(mainWindow,text="Click on add to add numbers")
label.pack()
def add_values():
result = int(entry1.get()) + int(entry2.get())
label['text'] = result
button = tkinter.Button(mainWindow,text="Add",command=add_values)
button.pack()
mainWindow.mainloop()
Upvotes: 3