每當用戶對輸入求和或減去輸入時,我都會嘗試在輸入框中輸入總數。但是它沒有顯示總數,而是將它們放在一行中。例如,我想添加 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()
uj5u.com熱心網友回復:
內部sum()(最好使用其他名稱作為sumPython 的標準函式),total始終初始化為零,因此
- 首先輸入15,然后
total將是15并插入到開頭tBox - 然后輸入1,
total將1(不是16)和在開始時插入tBox其中制作tBox115。
在插入新結果之前,您需要在total外部初始化為 0sum()并清除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()。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/369271.html
標籤:Python 特金特 和 计算器 tkinter-入口
