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

Discussion in 'Python' started by pablobarhamalzas@gmail.com, Jun 24, 2013.

  1. Guest

    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!
     
    , Jun 24, 2013
    #1
    1. Advertising

  2. Guest

    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.
     
    , Jun 24, 2013
    #2
    1. Advertising

  3. Peter Otten Guest

    wrote:

    > 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:

    >>> def f():

    .... print is_white
    .... is_white = 42
    ....
    >>> f()

    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:

    >>> def f():

    .... global is_white
    .... print is_white
    .... is_white = 42
    ....
    >>> is_white = "whatever"
    >>> f()

    whatever
    >>> f()

    42
     
    Peter Otten, Jun 24, 2013
    #3
  4. Op 24-06-13 21:47, 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
    ...

    --
    Antoon Pardon
     
    Antoon Pardon, Jun 24, 2013
    #4
  5. John Gordon Guest

    Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)

    In <> 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
    B is for Basil, assaulted by bears
    -- Edward Gorey, "The Gashlycrumb Tinies"
     
    John Gordon, Jun 24, 2013
    #5
  6. Guest

    Thank's to you all!

    Setting isWhite as global worked fine.
    I'll probably be back soon with another silly question, see you then :)
     
    , Jun 24, 2013
    #6
  7. On 24 June 2013 21:19, <> wrote:
    > 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.
     
    Joshua Landau, Jun 24, 2013
    #7
  8. On 24 June 2013 21:12, John Gordon <> wrote:
    > 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)
     
    Joshua Landau, Jun 24, 2013
    #8
  9. Dave Angel Guest

    On 06/24/2013 04:12 PM, John Gordon wrote:
    > In <> 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.
    >


    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.


    --
    DaveA
     
    Dave Angel, Jun 24, 2013
    #9
  10. John Gordon Guest

    Re: What's wrong with this code? (UnboundLocalError: local variable referenced before assignment)

    In <> Dave Angel <> writes:

    > > 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.


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

    --
    John Gordon A is for Amy, who fell down the stairs
    B is for Basil, assaulted by bears
    -- Edward Gorey, "The Gashlycrumb Tinies"
     
    John Gordon, Jun 24, 2013
    #10
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Moscatt
    Replies:
    2
    Views:
    9,840
    Peter Moscatt
    Mar 19, 2005
  2. Replies:
    2
    Views:
    5,328
    Diez B. Roggisch
    Feb 26, 2006
  3. Wang, Harry
    Replies:
    2
    Views:
    323
  4. Gabriel Rossetti
    Replies:
    3
    Views:
    989
    Hrvoje Niksic
    Dec 9, 2009
  5. ch1zra
    Replies:
    9
    Views:
    3,147
    danieldelay
    Jun 8, 2010
Loading...

Share This Page