如何在使用Python龟时按顺序选择颜色?

时间:2018-06-03 22:26:31

标签: python colors turtle-graphics

我有以下Python程序使用下面列出的颜色绘制方形设计。该程序仅对所有框应用粉红色,如何使语法重复下面列出的顺序颜色?

import turtle

def main():
    t = turtle.Turtle()
    t.hideturtle()
    t.speed(500)
    color = ["pink", "navy blue","red","forest green","cyan","magenta"]
    squaredesign(t,color)

def squaredesign(t,color):
    x = 100
    y = 100
    z = 1
    c = 0

    for i in range(10):

          t.up()
          t.goto(x,y)
          t.down()

          t.goto(x-x-x,y)
          t.goto(x-x-x,y-y-y)
          t.goto(x,y-y-y)
          t.goto(x,y)

          x+=-10
          y+=-10
          t.pencolor(color[c])

main()

1 个答案:

答案 0 :(得分:0)

我喜欢使用cycle中的itertools功能来实现此目的:

from itertools import cycle
from turtle import Turtle, Screen

COLORS = ["pink", "navy blue", "red", "forest green", "cyan", "magenta"]

def main():
    t = Turtle(visible=False)
    t.speed('fastest')

    color_iter = cycle(COLORS)

    squaredesign(t, color_iter)

def squaredesign(t, color_iter):
    x = 100
    y = 100

    for _ in range(10):

        t.pencolor(next(color_iter))

        t.penup()
        t.goto(x, y)
        t.pendown()

        t.goto(x - x - x, y)
        t.goto(x - x - x, y - y - y)
        t.goto(x, y - y - y)
        t.goto(x, y)

        x -= 10
        y -= 10

screen = Screen()

main()

screen.mainloop()

它永远不会用完颜色,因为它在结束后从头开始。模数运算符(%)是您可以用来解决此问题的另一种方法:

from turtle import Turtle, Screen

COLORS = ["pink", "navy blue", "red", "forest green", "cyan", "magenta"]

def main():
    t = Turtle(visible=False)
    t.speed('fastest')

    color_index = 0

    squaredesign(t, color_index)

def squaredesign(t, color_index):
    x = 100
    y = 100

    for _ in range(10):

        t.pencolor(COLORS[color_index])

        t.penup()
        t.goto(x, y)
        t.pendown()

        t.goto(x - x - x, y)
        t.goto(x - x - x, y - y - y)
        t.goto(x, y - y - y)
        t.goto(x, y)

        x -= 10
        y -= 10

        color_index = (color_index + 1) % len(COLORS)

screen = Screen()

main()

screen.mainloop()

这避免了额外的导入。