I am creating a calculator using tkinter, and I am having a hard time figuring out how I can only make the calculator solve what ever the user input once, and prevent further input into the next line (My output text widget has only two lines). I tried having the input only insert in the first line, but it only keeps having more inserted into the first line. Is this even possible to just prevent the buttons from being able to insert anything at all after hitting '=' until I hit clear?
#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')
Any reason you can't just store a variable that specifies whether your allowed to calculate. And update it after the first calculation and on clear?
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')