1

我正在使用 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')
4

1 回答 1

2

您不能只存储一个指定是否允许计算的变量的任何原因。并在第一次计算后更新它并明确?

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')
于 2020-08-13T02:32:25.283 回答