我如何使龟色褪色

时间:2017-12-10 23:13:04

标签: python-2.7 colors turtle-graphics

如何在python 2中使龟色褪色?

我希望有一个正方形,用乌龟慢慢地向中间消失。

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

2 个答案:

答案 0 :(得分:1)

您可以使用ontimer()定期运行将使用新颜色重绘矩形的功能。

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

答案 1 :(得分:1)

我同意@furas(+1)关于使用ontimer()但是如果您正在使用矩形形状,我会使用更简单的实现,使用乌龟来表示您的矩形并改变乌龟的颜色,而不是重绘任何东西:

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