【问题标题】:Calculator doesn't sum up the total计算器不总结总数
【发布时间】:2022-01-05 03:03:36
【问题描述】:

每当用户对输入进行求和或减去时,我都会尝试在输入框中输入总计。但是它没有显示总数,而是将它们放在一起。例如,我想添加 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()

【问题讨论】:

  • 首先不要使用except(真的),在这种情况下使用except TypeError:;您需要在插入新总和之前清除条目,而且您确实应该使用一个函数来更改条目
  • 它仍然没有总结,我做了你说的一切,它没有像以前那样打印彼此旁边的值,但它仍然没有总结它。

标签: python tkinter sum calculator tkinter-entry


【解决方案1】:

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() 中的相同问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多