每次单击乌龟时,如何将变量clicks
加1:
import turtle
jeff = turtle.Turtle()
jeff.shape("turtle")
jeff.color("blue")
clicks=0
def left(x,y):
jeff.left(90)
clicks=clicks+1
print "you have"+clicks+"clicks."
jeff.onclick(left)
当我键入此内容时,在clicks=clicks+1
行上会显示:
UnboundLocalError:之前引用的局部变量“ clicks” 作业
答案 0 :(得分:1)
变量clicks
是全局变量。任何要修改全局变量的函数都必须声明该变量global
:
from turtle import Turtle, mainloop
clicks = 0
def left(x, y):
global clicks
jeff.left(90)
clicks += 1
print "you have " + str(clicks) + " clicks."
jeff = Turtle()
jeff.shape("turtle")
jeff.color("blue")
jeff.onclick(left)
mainloop()