使用turtle.onclick()更改变量

时间:2019-06-26 23:22:45

标签: python python-2.7 turtle-graphics

每次单击乌龟时,如何将变量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”   作业

1 个答案:

答案 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()