Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable referenced before assignment - Python

Tags:

python

tkinter

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()
like image 983
user3080274 Avatar asked Oct 28 '25 20:10

user3080274


2 Answers

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.

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

like image 31
James Avatar answered Oct 30 '25 12:10

James