3

我正在尝试在这些正方形中填充颜色:

http://i.imgur.com/kRGgR.png

现在乌龟只填充这些正方形的角落,而不是整个正方形。

这是我的代码:

import turtle
import time
import random

print ("This program draws shapes based on the number you enter in a uniform pattern.")
num_str = input("Enter the side number of the shape you want to draw: ")
if num_str.isdigit():
    squares = int(num_str)

angle = 180 - 180*(squares-2)/squares

turtle.up

x = 0 
y = 0
turtle.setpos(x,y)


numshapes = 8
for x in range(numshapes):
    turtle.color(random.random(),random.random(), random.random())
    x += 5
    y += 5
    turtle.forward(x)
    turtle.left(y)
    for i in range(squares):
        turtle.begin_fill()
        turtle.down()
        turtle.forward(40)
        turtle.left(angle)
        turtle.forward(40)
        print (turtle.pos())
        turtle.up()
        turtle.end_fill()

time.sleep(11)
turtle.bye()

我试过四处走动turtle.begin_fill()end_fill()在许多地方都没有运气……使用 Python 3.2.3,谢谢。

4

4 回答 4

7

我还没有真正使用过龟,但看起来这可能是你想要做的。如果我假设这些调用的功能错误,请纠正我:

turtle.begin_fill() # Begin the fill process.
turtle.down() # "Pen" down?
for i in range(squares):  # For each edge of the shape
    turtle.forward(40) # Move forward 40 units
    turtle.left(angle) # Turn ready for the next edge
turtle.up() # Pen up
turtle.end_fill() # End fill.
于 2012-09-17T05:37:28.090 回答
3

您正在绘制一系列三角形,每个三角形都使用begin_fill()和。end_fill()您可能会做的是将您的调用移至内部循环begin_fill()end_fill()外部循环,因此您绘制一个完整的正方形,然后要求填充它。

于 2012-09-17T05:36:33.853 回答
1

使用填充

t.begin_fill()
t.color("red")
for x in range(4):
    t.fd(100)
    t.rt(90)
t.end_fill()
于 2015-05-26T03:38:47.363 回答
0

正如一些人所提到的,除了移动begin_fill()end_fill()循环之外,您的代码还有其他问题。例如,这是一个无操作:

turtle.up

即它什么都不做。(缺少括号。)这个测试:

if num_str.isdigit():

对您没有多大帮助,因为没有else处理错误的子句。(即当它不是数字时,下一条语句只是将字符串用作数字并失败。)这个计算似乎有点太复杂了:

angle = 180 - 180*(squares-2)/squares

最后应该有一个更干净的方式来退出程序。让我们解决所有这些问题:

from turtle import Screen, Turtle
from random import random

NUMBER_SHAPES = 8

print("This program draws shapes based on the number you enter in a uniform pattern.")

num_str = ""

while not num_str.isdigit():
    num_str = input("Enter the side number of the shape you want to draw: ")

sides = int(num_str)
angle = 360 / sides

delta_distance = 0
delta_angle = 0

screen = Screen()
turtle = Turtle()

for x in range(NUMBER_SHAPES):
    turtle.color(random(), random(), random())

    turtle.penup()
    delta_distance += 5
    turtle.forward(delta_distance)
    delta_angle += 5
    turtle.left(delta_angle)
    turtle.pendown()

    turtle.begin_fill()

    for _ in range(sides):
        turtle.forward(40)
        turtle.left(angle)
        turtle.forward(40)

    turtle.end_fill()

screen.exitonclick()
于 2019-12-08T20:21:52.003 回答