4

I'm trying to make a rainbow straight line but can't figure out the way the RGB values in turtle.pencolor() should change over time...

I tried using a hexadesimal increment from 000000 to FFFFFF but I got a a black to green line loop before getting an invalid color value.

cdlane
  • 40,441
  • 5
  • 32
  • 81
Demis
  • 197
  • 2
  • 10

2 Answers2

3

My guess is Python turtle's RGB-based colors are the wrong model for easily generating a rainbow line. Fortunately, you can import colorsys to work with a more appropriate model, like HSV, and have it convert those values to RGB:

from turtle import Screen, Turtle
from colorsys import hsv_to_rgb

RADIUS = 300
WIDTH = 100

screen = Screen()

turtle = Turtle(visible=False)
turtle.speed('fastest')  # because I have no patience
turtle.width(WIDTH)

turtle.penup()
turtle.sety(-RADIUS)
turtle.pendown()

for angle in range(360):
    turtle.pencolor(hsv_to_rgb(angle / 360, 0.75, 0.75))
    turtle.circle(RADIUS, 1)

screen.exitonclick()

Here we're just adjusting the hue based on the angle and leaving the saturation and value constant:

enter image description here

cdlane
  • 40,441
  • 5
  • 32
  • 81
0

Also, if you have even less patience, you can set the turtle module's "tracer" function to (0, 0)

eg. t.tracer(0, 0)

This will make the drawing appear instantly.

t.tracer(20, 0) will make the turtle go hyperspeed but still with some animation

you also need t.update() at the end if you use this method.

TheFunk
  • 981
  • 11
  • 39