Using turtle.onclick() to change a variable

Viewed 371

Every time the turtle is clicked, how would I have it increment the variable clicks by 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)

When I type this in, on the line clicks=clicks+1 it gives me:

UnboundLocalError: local variable 'clicks' referenced before assignment

1 Answers

The variable clicks is global. Any function that wants to modify a global variable has to declare that variable 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()
Related