Alex
Alex

Reputation: 23

Using turtle.onclick() to change a variable

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

Upvotes: 2

Views: 672

Answers (1)

cdlane
cdlane

Reputation: 41905

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

Upvotes: 1

Related Questions