What am I doing wrong?
from Tkinter import *
coordY = 400
win = Tk()
def key(event):
if str(event.char) == 'w':
coordY = coordY - 5
print coordY
def callback(event):
canvas.focus_set()
canvas = Canvas(win, width=800, height=450)
canvas.bind("<Key>", key)
canvas.bind("<Button-1>", callback)
canvas.pack()
photo = PhotoImage(file="image.gif")
canvas.create_image(400, coordY, image=photo)
naveY = 400
win.mainloop()
UnboundLocalError: local variable 'naveY' referenced before assignment
I want that when I press 'w' then the image moves up
Not knowing where your error comes from assuming theres more code, there could be a few different places. Does you error you get come from inside a class or function? if so try to set naveY as a global inside your function
global naveY
if your error traces to outside of a function or class is naveY defined before the line thats causing you the error? if so move your
naveY = 400
line accordingly
Not sure where naveY
(never mentioned anywhere in your code!) springs from, but here's a bug you have that could cause that exception (with a different variable name):
def key(event):
if str(event.char) == 'w':
coordY = coordY - 5
print coordY
coordY
is never defined (Python knows it's a local variable because you're assigning to it within the function), yet you're trying to subtract 5 from it -- what?!-)
I suspect this function is missing a first statement global coordY
to let Python know that it's not a local variable -- and that your reported problem with the mysterious naveY
is actually this very problem, and you just did some renaming in the code you're showing us, compared with the code you got that exception from:-)
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.