0

I'm trying to create a basic calculator and have a small problem I cant quite get. When you press the number buttons the input box will add the numbers until you then press a math key where the numbers will reset. What I cant work out is, say you put a number in like 8 then hit the inverse key, the output will show 0.125, then when you start typing again it will delete all things in the output window. Here is what I have but isn't working.

def button_click(number):
    if Flag == True:
        e.delete(0,END)
        e.insert(0, str(number))
    else:
        Current = e.get()
        e.delete(0,END)
        e.insert(0, str(Current) + str(number))
    global Flag
    Flag = False

and for the inv function

def button_inv():
    Current = float(e.get())
    e.delete(0, END)
    e.insert(0, 1/Current)
    global Flag
    Flag = True

Anyone have any ideas? Thanks.

7
  • Please repair the indentation of first snippet. Commented Jul 19, 2020 at 6:20
  • Explain "isn't working". What happens? Commented Jul 19, 2020 at 6:22
  • I will get the error UnboundLocalError: local variable 'Flag' referenced before assignment Commented Jul 19, 2020 at 6:23
  • 2
    Hi! Usually when getting exceptions, it is helpful to post the full stack-trace as well. That helps to know on which line the exception happened. Could you add it to your question please? Commented Jul 19, 2020 at 6:26
  • 3
    Also, I think the problem is you need to put "global Flag" at the start of your function. Commented Jul 19, 2020 at 6:27

1 Answer 1

1

Your placement of the global Flag is wrong, it should be placed at the beginning.

def button_click(number):
    global Flag
    if Flag == True:
        e.delete(0,END)
        e.insert(0, str(number))
    else:
        Current = e.get()
        e.delete(0,END)
        e.insert(0, str(Current) + str(number))
    Flag = False

and

def button_inv():
    global Flag
    Current = float(e.get())
    e.delete(0, END)
    e.insert(0, 1/Current)
    Flag = True

and declare Flag = False at the beginning of your code.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.