-1

I am trying to make a simple calculator with Python Tkinter. Below you can see a piece of code and a variable "sign" in it. I want the variable to serve as a way to tell the program that addition button of my calculator was pressed.

def addition():
    sign = "+"
    first_number = e.get()
    global first_converted
    first_converted = int(first_number)
    e.delete(0, END)

Further in the code, I want to make a function that will contain "if" statements for all of the scenarios of pressed buttons e.g. addition, division, multiplication, etc. However, Python does not see variable "sign".

def count():
    if sign == "+":
        pass
    e.delete(0, END)
    pass

I have tried declaring variable as global in the beginning of the code, but it did not help.

6
  • 1
    Can you share a minimal reproducible example Commented Aug 2, 2021 at 9:37
  • 1
    Variables are specific to some scope. The sign in addition is not the same as the sign in count. You should pass the values referred to by variables as arguments to other functions that need them. While you can also "pass" values as global, this is problematic when values need to be modified. Commented Aug 2, 2021 at 9:37
  • How about defining sign as a global variable? Commented Aug 2, 2021 at 9:37
  • 3
    I'd strongly recommend re-structuring the program so that there's no need to use global variables, but if you have to, sign has to be declared global in any function that assigns to it. Commented Aug 2, 2021 at 9:38
  • Does this answer your question? Python function global variables? Commented Aug 2, 2021 at 9:45

1 Answer 1

0

I would just pass on the sign argument as @MisterMiyagi descripes a bit:

def addition():
    sign = "+"
    first_number = e.get()
    global first_converted
    first_converted = int(first_number)
    e.delete(0, END)
    return sign #Returns sign

sign = addition()

def count(sign): #Takes sign as input
    if sign == "+":
        pass
    e.delete(0, END)
    pass

count(sign)

or make it global

sign = "+" #Or, by convention SIGN = "+"
def addition():
    first_number = e.get()
    global first_converted
    first_converted = int(first_number)
    e.delete(0, END)



def count(): #Takes sign as input
    if sign == "+":
        pass
    e.delete(0, END)
    pass
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.