Python龟图形填充问题

时间:2018-11-14 22:40:35

标签: python turtle-graphics

我应该为我的Python类绘制一个建筑物,并且fillcolor()函数针对两个形状完成其工作,但是对于最后一个形状,即使我完成了电路,可以说不会用我需要的颜色填充它:

import turtle

def main():
    turtle.setup(900, 900)
    cityscape(-300, -400, 300, 'gray')
    cityscape(0, -400, 300, 'gray')
    building(-300, -100, 'gray')
    turtle.speed(0)

def cityscape(x, y, width, color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pencolor('gray')
    turtle.fillcolor(color)
    turtle.pendown()
    turtle.begin_fill()
    for count in range(4):
        turtle.forward(width)
        turtle.left(90)
    turtle.end_fill()

def building(x, y, color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.fillcolor(color)
    turtle.pendown()
    turtle.begin_fill()
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(100)
    turtle.right(180)
    turtle.left(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(200)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(250)
    turtle.left(90)
    turtle.forward(70)
    turtle.left(90)
    turtle.forward(175)
    turtle.right(90)
    turtle.forward(80)
    turtle.right(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(70)
    turtle.right(90)
    turtle.forward(425)
    turtle.right(90)
    turtle.forward(425)


main()

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您将turtle.end_fill()函数的结尾留了building()。我还要写main()如下:

def main():
    turtle.setup(900, 900)
    turtle.speed('fastest')
    cityscape(-300, -400, 300, 'gray')
    cityscape(0, -400, 300, 'gray')
    building(-300, -100, 'gray')
    turtle.mainloop()

使用以上修复程序和一些样式更改来完成代码清单:

from turtle import Screen, Turtle

def main():
    screen = Screen()
    screen.setup(900, 900)

    yertle = Turtle(visible=False)
    yertle.speed('fastest')

    cityscape(yertle, -300, -400, 300, 'gray')
    cityscape(yertle, 0, -400, 300, 'gray')
    building(yertle, -300, -100, 'gray')

    screen.mainloop()

def cityscape(turtle, x, y, width, color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()

    turtle.color(color)

    turtle.begin_fill()
    for _ in range(4):
        turtle.forward(width)
        turtle.left(90)
    turtle.end_fill()

def building(turtle, x, y, color):
    turtle.penup()
    turtle.goto(x, y)
    turtle.pendown()

    turtle.color(color)

    turtle.begin_fill()
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(200)
    turtle.right(90)
    turtle.forward(100)
    turtle.right(90)
    turtle.forward(250)
    turtle.left(90)
    turtle.forward(70)
    turtle.left(90)
    turtle.forward(175)
    turtle.right(90)
    turtle.forward(80)
    turtle.right(90)
    turtle.forward(100)
    turtle.left(90)
    turtle.forward(70)
    turtle.right(90)
    turtle.forward(425)
    turtle.right(90)
    turtle.forward(425)
    turtle.end_fill()

main()