使用Python-turtle时如何按顺序选择颜色?

2024-04-23 20:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: import程序顺序颜色maindef语法绘制
1条回答
网友
1楼 · 发布于 2024-04-23 20:22:22

我喜欢使用来自itertoolscycle函数:

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

从而避免了额外的导入。你知道吗

相关问题 更多 >