<p>这个:</p>
<pre><code>color = [('white',0),('yellow',1),('green',2),('blue',3),('purple',4),('red',5),('black',6),('magenta',7),('pink',8),('brown',9)]
random.randint(0,9)
myTurtle.begin_fill(color)
</code></pre>
<p>相当于:</p>
^{pr2}$
<p>因为你没有把随机数赋给一个变量,在这个例子中,这个随机数被丢弃了。然后将整个颜色列表作为begin_fill()的参数传递。在</p>
<p>要获得随机颜色,可以执行以下操作:</p>
<pre><code>colors = ['white', 'yellow'....] #Note the change here.
rand_num = random.randint(0,9)
selected_color = colors[rand_num]
</code></pre>
<p>但是,python制造的东西<a href="https://docs.python.org/3/library/random.html#random.choice" rel="nofollow">easier</a>远不止这些:</p>
<pre><code>import random
colors = ['white', 'yellow'....]
selected_color = random.choice(colors) #Pick a random element from the colors list
</code></pre>
<p><strong>编辑:===========</strong></p>
<p>但是,您试图将参数传递给<code>begin_fill()</code>函数,但是<code>begin_fill()</code>不接受任何参数。默认情况下,<code>begin_fill()</code>使用<em>黑色</em>作为填充颜色。要将填充颜色设置为其他颜色,请使用以下函数之一:</p>
<pre><code>fill_color('red') #Sets fill color.
color('red') #Sets both pen and fill color.
</code></pre>
<p>以下是您可以做的一些示例:</p>
<pre><code>import turtle
import random
def drawPolygon(myTurtle,sideLength,numSides):
turnAngle = 360/numSides
for i in range(numSides):
myTurtle.forward(sideLength)
myTurtle.right(turnAngle)
def drawCircle(myTurtle, radius, fill_color="blue"):
circumference = 2 * 3.1415 * radius
sideLength = circumference / 360
myTurtle.color(fill_color) #color() sets pen and fill color
myTurtle.begin_fill() #The next shape that is drawn will be filled.
drawPolygon(myTurtle, sideLength, 360)
myTurtle.end_fill() #Disable filling.
def getRandomColor():
colors = ['yellow', 'green', 'blue']
rand_color = random.choice(colors)
return rand_color
rand_color = getRandomColor()
drawCircle(turtle, 40, rand_color)
turtle.exitonclick()
</code></pre>
<p>或者你可以这样做:</p>
<pre><code>import turtle
import random
def drawPolygon(myTurtle,sideLength,numSides):
turnAngle = 360/numSides
for i in range(numSides):
myTurtle.forward(sideLength)
myTurtle.right(turnAngle)
def getRandomColor():
colors = ['yellow', 'green', 'blue']
rand_color = random.choice(colors)
return rand_color
def drawCircle(myTurtle, radius):
circumference = 2 * 3.1415 * radius
sideLength = circumference / 360
rand_color = getRandomColor()
myTurtle.color(rand_color) #color() sets pen and fill color
myTurtle.begin_fill()
drawPolygon(myTurtle, sideLength, 360)
myTurtle.end_fill()
drawCircle(turtle, 40)
turtle.exitonclick()
</code></pre>
<p><strong>==============</strong></p>
<p>最后,颜色不是列表的好名字。列表名称应该是复数,例如:颜色、数字、单词;然后可以编写如下循环:</p>
<pre><code>for color in colors:
...
for number in numbers:
...
for word in words:
...
</code></pre>