Search code examples
tkinterglobal-variablesglobalcalculatornameerror

Global variable: name not defined


So I was trying to build a calculator:

def button_add():
    first_num = e.get()
    global f_num
    global math
    math = "add"
    f_num = int(first_num)
    e.delete(0, END)

def button_min():
    first_num = e.get()
    global f_num
    global math
    math = "min"
    f_num = int(first_num)
    e.delete(0, END)

def button_equal():
    second_num = e.get()
    e.delete(0, END)
    global math

    if math == "add":
        e.insert(0, f_num + int(second_num))
    elif math == "min":
        e.insert(0, f_num - int(second_num))


# Button command
equal = Button(m, text="=", font=("Mickey", 20), padx="2m", pady="2m", command=button_equal())
add = Button(m, text="+", font=("Mickey", 20), padx="2m", pady="2m", command=button_add())
min = Button(m, text="-", font=("Mickey", 20), padx="2m", pady="2m", command=button_min())

But after running it I've encountered an error:

   File "C:\Users\VAIO\PycharmProjects\project\calculator.py", line 89, in <module>
   equal = Button(m, text="=", font=("Mickey", 20), padx="2m", pady="2m",command=button_equal())
   File "C:\Users\VAIO\PycharmProjects\project\calculator.py", line 52, in button_equal
    if math == "add":
   NameError: name 'math' is not defined

I'm a beginner and I followed this guide, and I already double-checked the code so that it matches the one in the video. Why isn't global working? Does this have anything to do with the Python version I'm using?

Ps. I'm only including some of my code because the rest of them are irrelevant to my problem.


Solution

  • When you use command=button_equal(), button_equal() will be executed immediately. At that time math (better not use standard module name as variable name) is not defined.

    You should assign function reference (function name without ()) to command option instead:

    equal = Button(m, text="=", font=("Mickey", 20), padx="2m", pady="2m", command=button_equal)
    add = Button(m, text="+", font=("Mickey", 20), padx="2m", pady="2m", command=button_add)
    min = Button(m, text="-", font=("Mickey", 20), padx="2m", pady="2m", command=button_min)
    

    Note that if you click = before clicking + or -, same exception will be raised. So better initialize math first:

    math = None
    
    equal = Button(...)