Search code examples
pythontkintersumcalculatortkinter-entry

Calculator doesn't sum up the total


I am trying to have a total in the entry box whenever a user sum or subtract an input. however it does not show the total, it puts them together In one line. so for example, I want to add 15 and 1. first the user enters 15 then clicks on + then 1. instead of getting 16, they get 151.

import tkinter.messagebox
from tkinter import *
from tkinter import messagebox
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

window = Tk()
window.title("Calculator")
window.geometry("300x100")

# creating label for labelT
labelT = Label(text="Total: ")
labelT.grid()
# creating entry for labelT
tBox = Entry()
tBox.grid(column=1, row=0)
tBox.configure(state='disabled')
# creating entry for user number
numBox = Entry(window)
numBox.grid(column=1, row=1)


def sum():
    total = 0
    try:
        num = int(numBox.get())
    except:
        tk.messagebox.showwarning(title='Warning', message="Please enter numbers only")
        numBox.delete(0, tk.END)
    else:
        tBox.configure(state='normal')
        total += num
        tBox.insert(0, total)
        tBox.configure(state='disabled')


def subtract():
    total = 0
    try:
         num = int(numBox.get())
    except:
         tk.messagebox.showwarning(title='Warning', message="Please enter numbers only")
         numBox.delete(0, tk.END)
    else:
        tBox.configure(state='normal')
        total -= num
        tBox.insert(0, total)
        tBox.configure(state='disabled')


btn1 = Button(text="+", command=sum)
btn1.grid(column=0, row=2)
btn2 = Button(text="-", command=subtract)
btn2.grid(column=1, row=2)

window.mainloop()

Solution

  • Inside sum() (better use other name as sum is a standard function of Python), total is always initialised to zero, so

    • first enter 15, then total will be 15 and insert at the beginning of tBox
    • then enter 1, total will be 1 (not 16) and insert at the beginning of tBox which making tBox 115.

    You need to initialise total to 0 outside sum() and clear tBox before inserting the new result:

    # initialise total
    total = 0
    
    def sum():
        global total
        try:
            num = int(numBox.get())
        except:
            tk.messagebox.showwarning(title='Warning', message="Please enter numbers only")
            numBox.delete(0, tk.END)
        else:
            tBox.configure(state='normal')
            # update total
            total += num
            # clear tBox
            tBox.delete(0, END)
            # insert new result into tBox
            tBox.insert(0, total)
            tBox.configure(state='disabled')
    

    Note that same issue in subtract() as well.