问题描述
我正在使用tkinter创建一个计算器,并且很难弄清楚如何只能使计算器解决用户一次输入的问题,并防止进一步输入到下一行(我的输出文本小部件只有两行)。我尝试将输入仅插入第一行,但只会继续在第一行插入更多输入。甚至有可能只是阻止按钮在按下'='之后直到我按下清除按钮时根本不能插入任何东西吗?
#function handles all calculations and inputs
def calc(data):
#gets last character in output
last_value = output.get('end -2 chars')
#condition how data should be inserted
if data.isnumeric() or data == '.':
output.insert('end',data)
if last_value == '.' and data == '.': #prevents duplicating decimals
output.replace('end -3 chars','end -1 chars',data)
elif data in "+-*/":
output.insert('end',data)
if last_value in "+-/*": #prevents duplicating operators also replaces existing operators
output.replace('end-3c','end-1c',data)
elif data == 'C':
output.delete('1.0','end')
#solves equation
elif data == '=':
equation = output.get('end -1 lines linestart','end -1 lines lineend')
try:
answer = eval(equation)
output.insert('end','\n' + str(answer))
except SyntaxError:
output.insert('end','\n' + 'ERROR: SYNTAX')
except ZeroDivisionError:
output.insert('end','\n' + 'ERROR: 0 DIVISION')
解决方法
由于任何原因,您不能只存储一个变量,该变量指定是否允许计算。并在第一次计算后更新并清除?
def calc(data):
#gets last character in output
last_value = output.get('end -2 chars')
#condition how data should be inserted
if data.isnumeric() or data == '.' and can_calculate: #make sure we're allowed to calculate/update
output.insert('end',data)
if last_value == '.' and data == '.': #prevents duplicating decimals
output.replace('end -3 chars','end -1 chars',data)
elif data in "+-*/" and can_calculate: #make sure we're allowed to calculate/update
output.insert('end',data)
if last_value in "+-/*": #prevents duplicating operators also replaces existing operators
output.replace('end-3c','end-1c',data)
elif data == 'C':
output.delete('1.0','end')
can_calculate=True #update var to reflect a calculation because we cleared
#solves equation
elif data == '=' and can_calculate:
equation = output.get('end -1 lines linestart','end -1 lines lineend')
try:
answer = eval(equation)
output.insert('end','\n' + str(answer))
can_calculate = False #update var to reflect a calculation because we calculated
except SyntaxError:
output.insert('end','\n' + 'ERROR: SYNTAX')
except ZeroDivisionError:
output.insert('end','\n' + 'ERROR: 0 DIVISION')