What's wrong with this code? (UnboundLocalError: local variablereferenced before assignment)

P

pablobarhamalzas

Hi there! I'm quite new to programming, even newer in python (this is actually the first thing I try on it), and every other topic I've seen on forums about my problem doesn't seem to help.

So, the following lines are intended to draw a white square (which it does), turn it to blue when you click on it, and back to white when you click on it again (and so on). Here's what I wrote (python 3 syntax):


from tkinter import *

root = Tk()
root.geometry("500x500")

w = Canvas(root, width=500, height=500)
w.pack()

coords = (x1, y1, x2, y2) = (100, 100, 200, 200)

rect = w.create_rectangle(coords, fill="white")
isWhite = True

def change(event):
if event.x > x1 and event.x < x2 and event.y > y1 and event.y < y2:
if isWhite:
w.itemconfig(rect, fill="blue")
isWhite = False
else:
w.itemconfig(rect, fill="white")
isWhite = True

w.bind("<Button-1>", change)

root.mainloop()


The problem occurs when clicking on the white square. The following error appears:
"if isWhite:
UnboundLocalError: local variable 'isWhite' referenced before assignment"

However, the isWhite variable is clearly defined at "True" a few lines before.
Also, if I remove the lines that change isWhite to False if it's True and viceversa, the program doesn't throw any error, but obviously doesn't do what I want it to do (it only changes the square color once, as isWhite stays set to True).

What can the problem be? I'm sure it's something really simple, but I don't get it... Thank's!
 
P

pablobarhamalzas

Just before anyone says, the reason I bind to the Canvas instead of binding directly to the rectangle is because I plan to add more squares in the future.
Cheers.
 
P

Peter Otten

Hi there! I'm quite new to programming, even newer in python (this is
actually the first thing I try on it), and every other topic I've seen on
forums about my problem doesn't seem to help.

So, the following lines are intended to draw a white square (which it
does), turn it to blue when you click on it, and back to white when you
click on it again (and so on). Here's what I wrote (python 3 syntax):


from tkinter import *

root = Tk()
root.geometry("500x500")

w = Canvas(root, width=500, height=500)
w.pack()

coords = (x1, y1, x2, y2) = (100, 100, 200, 200)

rect = w.create_rectangle(coords, fill="white")
isWhite = True

def change(event):
if event.x > x1 and event.x < x2 and event.y > y1 and event.y < y2:
if isWhite:
w.itemconfig(rect, fill="blue")
isWhite = False
else:
w.itemconfig(rect, fill="white")
isWhite = True

w.bind("<Button-1>", change)

root.mainloop()


The problem occurs when clicking on the white square. The following error
appears: "if isWhite:
UnboundLocalError: local variable 'isWhite' referenced before assignment"

However, the isWhite variable is clearly defined at "True" a few lines
before. Also, if I remove the lines that change isWhite to False if it's
True and viceversa, the program doesn't throw any error, but obviously
doesn't do what I want it to do (it only changes the square color once, as
isWhite stays set to True).

What can the problem be? I'm sure it's something really simple, but I
don't get it... Thank's!

Python statically determines the scope of a variable -- if you rebind a name
it assumes that the variable is local:
.... print is_white
.... is_white = 42
....Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'is_white' referenced before assignment

The fix is to tell Python that you want to access the global variable:
.... global is_white
.... print is_white
.... is_white = 42
....42
 
A

Antoon Pardon

Op 24-06-13 21:47, (e-mail address removed) schreef:
Hi there! I'm quite new to programming, even newer in python (this is actually the first thing I try on it), and every other topic I've seen on forums about my problem doesn't seem to help.

So, the following lines are intended to draw a white square (which it does), turn it to blue when you click on it, and back to white when you click on it again (and so on). Here's what I wrote (python 3 syntax):


from tkinter import *

root = Tk()
root.geometry("500x500")

w = Canvas(root, width=500, height=500)
w.pack()

coords = (x1, y1, x2, y2) = (100, 100, 200, 200)

rect = w.create_rectangle(coords, fill="white")
isWhite = True

def change(event):
if event.x> x1 and event.x< x2 and event.y> y1 and event.y< y2:
if isWhite:
w.itemconfig(rect, fill="blue")
isWhite = False
else:
w.itemconfig(rect, fill="white")
isWhite = True

w.bind("<Button-1>", change)

root.mainloop()


The problem occurs when clicking on the white square. The following error appears:
"if isWhite:
UnboundLocalError: local variable 'isWhite' referenced before assignment"

However, the isWhite variable is clearly defined at "True" a few lines before.

No it is not.

In Python, when you assign to a variable within a function, that
variable will be treated as a local variable. If you have a global
variable with the same name, that global variable will just for
the duration of the function become inaccessible.

The quick solution in this case is to include a global statement.
Something like

def change(event)
global isWhite
...
 
J

John Gordon

In said:
isWhite = True

def change(event):
if event.x > x1 and event.x < x2 and event.y > y1 and event.y < y2:
if isWhite:
w.itemconfig(rect, fill="blue")
isWhite = False
else:
w.itemconfig(rect, fill="white")
isWhite = True

w.bind("<Button-1>", change)

root.mainloop()
The problem occurs when clicking on the white square. The following error
appears:
"if isWhite:
UnboundLocalError: local variable 'isWhite' referenced before assignment"
However, the isWhite variable is clearly defined at "True" a few lines
before.

Since you're new to programming, this might be a bit tricky to explain,
but I'll do my best. :)

The problem is that change() isn't being executed here; instead it's being
executed from within root.mainloop(), whenever the user presses button-1.

And within root.mainloop(), there is no variable called isWhite.
 
P

pablobarhamalzas

Thank's to you all!

Setting isWhite as global worked fine.
I'll probably be back soon with another silly question, see you then :)
 
J

Joshua Landau

Thank's to you all!

Setting isWhite as global worked fine.
I'll probably be back soon with another silly question, see you then :)

By the way, it's normally bad to use globals like this. When you're
learning it's something you just do, though; it's fine for now.
 
J

Joshua Landau

Since you're new to programming, this might be a bit tricky to explain,
but I'll do my best. :)

The problem is that change() isn't being executed here; instead it's being
executed from within root.mainloop(), whenever the user presses button-1.

And within root.mainloop(), there is no variable called isWhite.

Sorry, but I don't think you're right. Functions "carry" their
contexts around with them, so that shouldn't matter

(See Peter and Antoon's comments for explanation of what I think it is)
 
D

Dave Angel

Since you're new to programming, this might be a bit tricky to explain,
but I'll do my best. :)

The problem is that change() isn't being executed here; instead it's being
executed from within root.mainloop(), whenever the user presses button-1.

And within root.mainloop(), there is no variable called isWhite.

Actually that's irrelevant. Whether or not there's one global with the
same name, or twenty-three object attributes with the same name, the
fact that there's a binding of the local makes that name a local. The
only way to avoid that is not to bind, or to use global or nonlocal
declarations.


Pablo: Global variables are generally frowned upon, unless they're
constant. If they're constant, use ALLCAPS to indicate that. Since
this is not, it would normally be an attribute of some object, in your
case, possibly the object w. And of course, w should have been an
argument to the function as well, since you're operating on it. But you
may be stuck with that, because of tkinter's design. Anyway, you can assign
w.isWhite = True

and access
if w.isWhite

with impunity, since w is not being bound inside the function.


When you need to pass extra arguments that the event model doesn't allow
for, one approach is to use functools.partial().

And it's also possible that there's a method (in tkinter) on event that
let's you find the object that it's acting upon, w. In this case, you
could avoid needing a global at all, which would be a big improvement.
Especially when you decide to have multiple such boxes, and want each to
be able to toggle colors independently.
 
J

John Gordon

Actually that's irrelevant. Whether or not there's one global with the
same name, or twenty-three object attributes with the same name, the
fact that there's a binding of the local makes that name a local. The
only way to avoid that is not to bind, or to use global or nonlocal
declarations.

Quite right. I should have verified my answer before posting. Thanks
for setting me straight. :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,222
Members
46,810
Latest member
Kassie0918

Latest Threads

Top