What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)
John Gordon
gordon at panix.com
Mon Jun 24 16:12:49 EDT 2013
In <b3d3518a-f24a-4c32-a41a-b99145753528 at googlegroups.com> pablobarhamalzas at gmail.com writes:
> 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.
--
John Gordon A is for Amy, who fell down the stairs
gordon at panix.com B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"
More information about the Python-list
mailing list