[英]In Python turtle graphics, color() can't iterate over a list of colors
從海龜圖形開始。 我想創建一個程序,以一定的角度打印一定數量的正方形(正方形和角度的數量將根據用戶輸入而變化)。 流程將是 -
我的代碼的問題實際上出在第 3 步。我創建了一個 function 列表,其中包含 colors 列表,它將填充海龜中的 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() 只選擇列表中的最后一項的線索為零。 任何幫助,將不勝感激。 另外,請原諒我凌亂的代碼,仍然是菜鳥。 #TIA
當您執行顏色 function 時,您的循環為當前繪制的正方形選擇每種顏色一次並分配該顏色。 因此,循環的每次迭代都會覆蓋以前的顏色,使列表中的最后一種顏色成為每個正方形的選定顏色。
您可以錯開 colors,方法是傳遞到目前為止已繪制的方格數並將該數字的模數與顏色列表的長度相乘,以確保每次調用時選擇不同的顏色。
我在下面的代碼中做了一些內聯注釋以幫助解釋。
例如:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.