【问题标题】:How to choose colors in sequence while using Python turtle?使用 Python turtle 时如何按顺序选择颜色?
【发布时间】:2018-11-13 06:06:41
【问题描述】:

我有下面的 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()

【问题讨论】:

  • t.pencolor(color[i])
  • 谢谢。它适用于前 6 个方块并给出“索引错误:列表索引超出范围”。选完最后一种颜色后如何重复颜色?
  • 您是如何尝试解决问题的?
  • 我替换了变量并绘制了框,但在使用了 6 种颜色后它停止了,所以我使用了一个 while 循环将 c 重置为零,但它没有循环。
  • 如果 c == 4:c = 0 否则:c+=1

标签: python colors turtle-graphics


【解决方案1】:

我喜欢使用 itertools 中的 cycle 函数来实现此目的:

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

这避免了额外的导入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-15
    • 2019-07-04
    • 2015-04-10
    • 2013-10-26
    • 1970-01-01
    • 2016-03-08
    相关资源
    最近更新 更多