简体   繁体   中英

Variable referenced before assignment - Python

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()

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM