计算器不汇总总数



每当用户对输入求和或相减时,我都试图在输入框中输入一个总数。然而,它没有显示总数,而是将它们放在一行中。例如,我想加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

在插入新结果之前,您需要将total初始化为sum()之外的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()中的相同问题。

相关内容

  • 没有找到相关文章

最新更新