[英]tkinter addition/subtraction calculator problem
我試圖構建一個簡單的計算器,將當前總和顯示為標簽,當通過輸入窗口中的“ ADD”和“ SUBTRACT”按鈕添加或減去數字時,標簽會發生變化。 該小部件僅在視覺上起作用,但無法計算我想要的值。
我試圖將currentsum值添加為0
from tkinter import*
def addition():
currentsum=float(e1.get())
e1.insert(INSERT,str(currentsum))
def subtraction():
currentsum=currentsum-float(e1.get())
e1.insert(INSERT,str(currentsum))
def reset():
currentsum=0
e1.insert(INSERT,str(currentsum))
window=Tk()
currentsum=0
l1=Label(window,text="current sum:")
l1.grid(row=0, column=0)
l2=Label(window,text=str(currentsum))
l2.grid(row=0,column=1)
e1=Entry(window)
e1.grid(row=1,column=0)
b1=Button(window,text="ADD(+)",command=addition)
b2=Button(window,text="SUBTRACT(-)",command=subtraction)
b3=Button(window,text="RESET",command=reset)
b1.grid(row=2,column=0)
b2.grid(row=2,column=1)
b3.grid(row=2,column=2)
window.mainloop()
這是錯誤消息:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Administrator\Downloads\sdfgasgasg.py", line 8, in subtraction
currentsum=currentsum-float(e1.getenter code here())
UnboundLocalError: local variable 'currentsum' referenced before assignment
您正在嘗試在全局上下文中的方法中使用currentsum
,但在本地方法中的變量未正確處理。 原因是因為currentsum
是在您的方法之后定義的。 移動它,使其在方法之前定義。 另外,如果您要確保變量在每次調用方法時都保持其更改,則“最簡單”的方法是在所有方法中插入global currentsum
,以便您能夠訪問currentsum
並對其進行修改。
另外,我建議將顯示當前總和的文本替換為運行總計,而不是通過將其插入文本字段來顯示此總和。 插入將使用currentsum
在文本字段中添加當前內容,這可能不是您想要的。 另外,您的加法中存在一個錯誤,您應該累積從文本字段讀取的值,而不是替換它。
因此:
from tkinter import*
currentsum=0
def addition():
global currentsum # New
currentsum+=float(e1.get()) # Fix
#e1.insert(INSERT,str(currentsum))
l2['text'] = str(currentsum) # Change
def subtraction():
global currentsum # New
currentsum=currentsum-float(e1.get())
#e1.insert(INSERT,str(currentsum))
l2['text'] = str(currentsum) # Change
def reset():
global currentsum # New
currentsum=0
#e1.insert(INSERT,str(currentsum))
l2['text'] = str(currentsum) # Change
window=Tk()
l1=Label(window,text="current sum:")
l1.grid(row=0, column=0)
l2=Label(window,text=str(currentsum))
l2.grid(row=0,column=1)
e1=Entry(window)
e1.grid(row=1,column=0)
b1=Button(window,text="ADD(+)",command=addition)
b2=Button(window,text="SUBTRACT(-)",command=subtraction)
b3=Button(window,text="RESET",command=reset)
b1.grid(row=2,column=0)
b2.grid(row=2,column=1)
b3.grid(row=2,column=2)
window.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.