You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Turtle中color()无法遍历颜色列表的问题求助

问题分析与解决

问题原因

你的chooseColor函数存在逻辑错误:函数内部循环遍历颜色列表时,会连续三次调用color(i),依次将颜色设为orange、yellow、red,但循环结束后,最后一次设置的颜色是列表的最后一项red。所以每次调用chooseColor,最终都会把画笔颜色固定为red,导致所有正方形颜色相同。

解决方案

我们需要让每个正方形按顺序使用颜色列表中的颜色,甚至当正方形数量超过颜色列表长度时,可以循环复用颜色。这里提供两种简单的修改方式:

方式一:使用迭代器逐个取色

通过创建颜色列表的迭代器,每次调用取色函数时取下一个颜色,迭代器耗尽后自动循环:

from turtle import *

# 定义全局颜色列表和迭代器
colorOption = ['orange', 'yellow', 'red']
color_iter = iter(colorOption)

def chooseColor():
    try:
        # 取下一个颜色
        current_color = next(color_iter)
    except StopIteration:
        # 迭代器耗尽后重置,循环取色
        global color_iter
        color_iter = iter(colorOption)
        current_color = next(color_iter)
    color(current_color)

def squareFill():
    chooseColor()
    begin_fill()
    for _ in range(4):
        forward(100)
        right(90)
    end_fill()

def multiSquare():
    noOfsquares = int(input("How many squares do you want to print?:\n"))
    angle = int(input("At what angle should the squares be from each other?:\n"))  
    for _ in range(noOfsquares):
        squareFill()
        right(angle)

multiSquare()

方式二:通过索引控制颜色切换

在主函数中维护一个颜色索引,每次绘制正方形时传递当前索引对应的颜色,用取模运算实现循环复用:

from turtle import *

colorOption = ['orange', 'yellow', 'red']

def squareFill(color):
    color(color)
    begin_fill()
    for _ in range(4):
        forward(100)
        right(90)
    end_fill()

def multiSquare():
    noOfsquares = int(input("How many squares do you want to print?:\n"))
    angle = int(input("At what angle should the squares be from each other?:\n"))  
    for i in range(noOfsquares):
        current_color = colorOption[i % len(colorOption)]
        squareFill(current_color)
        right(angle)

multiSquare()

说明

第二种方式更简洁直接,i % len(colorOption)的写法能保证即使输入的正方形数量超过颜色列表长度,也能不断循环使用现有颜色。

内容的提问来源于stack exchange,提问作者khonshu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:50:20