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