John
John

Reputation: 11

How do I make a turtle color fade

How do I make a turtle color fade in python 2?

I want to have a square that slowly fades to the middle with a turtle.

from turtle import Turtle
t = Turtle()
t.begin_fill()
t.color('white')
for counter in range(4):
    t.forward(100)
    t.right(90)
    t.color(+1)
t.end_fill()

Upvotes: 1

Views: 2650

Answers (2)

cdlane
cdlane

Reputation: 41872

I agree with @furas (+1) about using ontimer() but if you're working with a rectanglar shape, I'd go with a simpler implementation, using a turtle to represent your rectangle and changing the turtle's color rather than redrawing anything:

from turtle import Turtle, Screen, mainloop

CURSOR_SIZE = 20
DELAY = 75
DELTA = 0.05

def fade(turtle, gray=0.0):

    turtle.color(gray, gray, gray)  # easily upgradable to a hue

    if gray < 1.0:
        screen.ontimer(lambda: fade(turtle, min(gray + DELTA, 1.0)), DELAY)
    else:
        turtle.hideturtle()  # disappear altogether

screen = Screen()

rectangle = Turtle('square')
rectangle.shapesize(90 / CURSOR_SIZE, 100 / CURSOR_SIZE)  # "draw" rectangle

fade(rectangle)

mainloop()

Upvotes: 1

furas
furas

Reputation: 142651

You can use ontimer() to run periodically function which will redraw rectangle with new color.

import turtle as t

def rect(c):
    t.color(c)
    t.begin_fill()
    for _ in range(4):
        t.forward(100)
        t.right(90)
    t.end_fill()    

def fade():
    global c

    # draw         
    rect(c)

    # change color
    r, g, b = c
    r += 0.1
    g += 0.1
    b += 0.1
    c = (r, g, b)

    # repeat function later
    if r <= 1.0 and g <= 1.0  and b <= 1.0:
        # run after 100ms
        t.ontimer(fade, 100)

# --- main ---

# run fast
t.speed(0)

# starting color
c = (0,0,0) # mode 1.0 color from (0.0,0.0,0.0) to (1.0,1.0,1.0)

# start fadeing
fade()

# start "the engine" so `ontimer` will work
t.mainloop()

Upvotes: 1

Related Questions