In Python when using the turtle module, we can easily create a random color turtle with the help of the randint() function.

import turtle
from random import randint

turtle.colormode(255)

t = turtle.Turtle()

t.color(randint(0,255),randint(0,255),randint(0,255))

The Python turtle module provides us with many functions which allow us to add color to the shapes we draw. There are many options for colors in the turtle module which can add life to our designs.

When creating graphics, sometimes it’s cool to be able to generate random colors to make random colored shapes or designs.

We can generate random colors using RGB colors. To use RGB colors, we change the color mode to RGB mode (‘255’), and then we use the randint() function from the random module to generate random numbers in the range 0 to 255.

With the help of the randint() function, we can create a random color turtle in our Python program.

Let’s create a program which will randomly generate a new color for our turtle after each move it makes.

To do so, we just need to call the color() function with three random inputs.

Below is an example in Python of how to get a random color turtle.

import turtle
from random import randint

turtle.colormode(255)

t = turtle.Turtle()

def moveTurtle(x):
    t.color(randint(0,255),randint(0,255),randint(0,255))
    t.forward(5)
    if x % 3 == 0:
        t.right(45)
    else:
        t.left(25)

for x in range(0,100):
    moveTurtle(x)

random color turtle python

Another application of get random color turtles when drawing a shape is creating a spiral which changes color as it gets bigger and bigger.

Below is an example of a spiral that changes color as it gets bigger in Python.

import turtle
from random import randint

turtle.colormode(255)

t = turtle.Turtle()

def draw_spiral(starting_radius, loops):
    for i in range(0, loops):
        t.pencolor(randint(0,255),randint(0,255),randint(0,255))
        t.circle(starting_radius + i, 60)      

draw_spiral(10, 50)

turtle spiral random colors

Hopefully this article has been useful for you to learn how to generate a random color turtle in Python.

Categorized in:

Python,

Last Update: March 1, 2024