4

I am getting the error...

a = a + b
UnboundLocalError: local variable 'a' referenced before assignment

I don't understand why the error occurs if I have assigned the two variables a and b at the start.

from tkinter import *

a = 10
b = 12
def stopProg(e):
    root.destroy()

def addNumbers(e):
    a = a + b
    label1.configure(text= str(a))

root=Tk()
button1=Button(root,text="Exit")
button1.pack()
button1.bind('<Button-1>',stopProg)
button2=Button(root,text="Add numbers")
button2.pack()
button2.bind('<Button-1>',addNumbers)
label1=Label(root,text="Amount")
label1.pack()

root.mainloop()

3 Answers 3

9

Whenever you modify a global variable inside a function, you need to first declare that variable as being global.

So, you need to do this for the global variable a since you modify it inside addNumbers:

def addNumbers(e):
    global a
    # This is the same as: a = a + b
    a += b
    # You don't need str here
    label1.configure(text=a)

Here is a reference on the global keyword.


Also, I would like to point out that your code can be improved if you use the command option of Button:

from tkinter import *

a = 10
b = 12
def stopProg():
    root.destroy()

def addNumbers():
    global a
    a += b
    label1.configure(text=a)

root=Tk()
button1=Button(root, text="Exit", command=stopProg)
button1.pack()
button2=Button(root, text="Add numbers", command=addNumbers)
button2.pack()
label1=Label(root, text="Amount")
label1.pack()

root.mainloop()

There is never a good reason to use binding in place of the command option.

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

3 Comments

Out of all the lectures I have went to, I have never been shown this. Thank you very much!
Can I ask what is 'e' for in here - 'def stopProg(e)' ? Thanks.
@Amber.G - It is to hold the event object that will be passed to the function by .bind(). You'll notice though that I removed it from the updated code since we are now using command, which does not send an event object.
2

Here is your answer :

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope.

Please read this : http://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Comments

1

You are modifying a global variable. By default, you can read values from global variables, without declaring them as global, but to modify them you need to declare them as global like this

global a
a = a + b

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.