Animations and Interactive Programming

Interactive Programming: Click with Colors

If we want some other statements to be executed in addition to the standard turtle.goto(x,y) function, we can define a new method with two parameters to be used as x and y coordinates to do so.

import turtle
import random
import math

turtle.setup(500, 500)
screen = turtle.Screen()
turtle.title("Turtle Keys")
turtle.pensize(3)

colors = ("orange", "pink", "yellow", "green", "blue", "purple", "magenta", "cyan")
drawing = False


def goto_and_do_whatever_required(x, y):
    global drawing
    if(drawing):
        return
    if(y > 150):
        return
    drawing = True
    turtle.goto(x, y)
    turtle.color(colors[random.randint(0, len(colors)-1)])
    drawing = False


screen.onscreenclick(goto_and_do_whatever_required)

turtle.done()

Adding the goto_and_do_whatever_required function will move the turtle to the (x, y) coordinates of the clicked position, and change the color of the turtle.

We do not want user clicks before the painting is over. The is statements

if(drawing):
    return

will prevent turtle from start drawing before the previous drawing is over.

We are also going to use the upper part of the paint area for some buttons. The if statement

if(y > 150):
    return

will prevent turtle from painting into the button area.