每次单击乌龟时,如何将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”
  分配

最佳答案

变量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()

关于python - 使用turtle.onclick()更改变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56782081/

10-09 03:03