从 turtle 的图形开始.我想创建一个程序,以一定的Angular 打印一定数量的方块(方块和Angular 会根据用户输入的不同而有所不同).流量将会是-

  1. 用户输入正方形的数量
  2. 用户输入每个方块之间的Angular
  3. 生成的每个正方形应该有不同的 colored颜色

我的代码的问题实际上是在步骤3中.我创建了一个带有 colored颜色 列表的函数,该函数将填充Turtle中的color()方法.然而,color()方法总是以获取列表中的最后一个元素结束.

from turtle import *

##Function to populate the color() method from a list of predefined colors. color(i) always populates with 'red' when I run the code.
def chooseColor():
        colorOption = ['orange', 'yellow', 'red']
        for i in colorOption:
                color(i)

#Function to create filled squares
def squareFill():
        chooseColor()
        begin_fill()
        for i in range (4):
                forward(100)
                right(90)
        end_fill()

#Function to create multiple squares
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):
        squareFill()
        right(angle)

multiSquare()

我不知道为什么COLOR()只 Select 列表中的最后一项.任何帮助都将不胜感激.另外,请原谅我乱七八糟的代码,仍然是个菜鸟.#TIA

推荐答案

当您执行COLOR函数时,您的循环为当前绘制的正方形 Select 一次每种 colored颜色 并分配该 colored颜色 .因此,循环的每次迭代都会覆盖前一种 colored颜色 ,从而使列表中的最后一种 colored颜色 成 for each 正方形的选定 colored颜色 .

您可以交错 colored颜色 ,方法是传递到目前为止绘制的方块的计数,并将该数字的模取与 colored颜色 列表的长度,以确保每次调用它时它 Select 不同的 colored颜色 .

我在下面的代码中做了一些内联注释,以帮助解释.

例如:

from turtle import *

##Function to populate the color() method from a list of predefined colors. color(i) always populates with 'red' when I run the code.

def chooseColor(count):  # now it will cycle through each color when called
        colorOption = ['orange', 'yellow', 'red']
        color(colorOption[count % len(colorOption)])

#Function to create filled squares
def squareFill(count): 
        chooseColor(count) # pass the incrementing number to color func
        begin_fill()
        for i in range (4):
                forward(100)
                right(90)
        end_fill()

#Function to create multiple squares
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 count in range (noOfsquares):  # take this incrementing number
        squareFill(count)   # pass it to the square builder
        right(angle)

multiSquare()

Python相关问答推荐

2维数组9x9,不使用numpy.数组(MutableSequence的子类)

大Pandas 胚胎中产生组合

使用新的类型语法正确注释ParamSecdecorator (3.12)

如何让剧作家等待Python中出现特定cookie(然后返回它)?

如何从具有不同len的列表字典中创建摘要表?

' osmnx.shortest_track '返回有效源 node 和目标 node 的'无'

如何过滤包含2个指定子字符串的收件箱列名?

如何在Raspberry Pi上检测USB并使用Python访问它?

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

在含噪声的3D点网格中识别4连通点模式

如何使用Pandas DataFrame按日期和项目汇总计数作为列标题

UNIQUE约束失败:customuser. username

手动设置seborn/matplotlib散点图连续变量图例中显示的值

在pandas/python中计数嵌套类别

Polars Group by描述扩展

如何在Django模板中显示串行化器错误

Seaborn散点图使用多个不同的标记而不是点

我怎么才能用拉夫分拣呢?

正在try 让Python读取特定的CSV文件

Matplotlib中的曲线箭头样式