【问题标题】:How do I make a turtle color fade如何让乌龟颜色变淡
【发布时间】:2018-05-24 11:26:45
【问题描述】:

如何在 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()

【问题讨论】:

  • 也许使用ontimer 运行周期性函数,它将用新颜色重绘它。

标签: python-2.7 colors turtle-graphics


【解决方案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()

【讨论】:

    【解决方案2】:

    我同意 @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()
    

    【讨论】:

    • @John,您是在使用标准的、完整的 Python 安装,还是在使用在线 Python,例如 Trinket.io,它有更多的限制,在海龟的情况下,部分库?
    猜你喜欢
    • 2015-12-29
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 1970-01-01
    • 2013-12-17
    • 1970-01-01
    • 2022-12-09
    • 2020-08-11
    相关资源
    最近更新 更多