计算器不计算总数

Calculator doesn't sum up the total

每当用户对输入求和或减去输入时,我都试图在输入框中输入总计。但是它不显示总数,而是将它们放在一行中。例如,我想添加 15 和 1。首先用户输入 15,然后单击 +,然后单击 1。他们得到的不是 16,而是 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()

sum()中(最好使用其他名称,因为sum是Python的标准函数),total总是初始化为零,所以

  • 先输入15,那么total就是15,插入到tBox
  • 的开头
  • 然后输入 1,total 将是 1(不是 16)并插入到 tBox 的开头,从而使 tBox 115.

您需要在 sum() 之外将 total 初始化为 0 并在插入新结果之前清除 tBox:

# 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')

请注意 subtract() 中也有同样的问题。