【问题标题】:turtle graphics Turtle slows down海龟图形 海龟减速
【发布时间】:2018-09-27 03:39:05
【问题描述】:

我将乌龟设置为最快,当我单独运行第一个循环时它很好,但随着我添加更多,它变得与单独执行第一个循环时相当。我不知道这是否仅仅是因为绘图的复杂性,但完成形状需要相当长的时间。有什么办法可以解决这个问题吗?

import turtle

turtle.bgcolor("Red")
turtle.color("Yellow", "Pink")
turtle.shape("turtle")
turtle.begin_fill()
turtle.speed("fastest")

while True:
    turtle.forward(300)
    turtle.left(179)
    turtle.circle(20)
    if abs(turtle.pos()) < 1:
        break

turtle.setheading(270)



while True:
    turtle.forward(300)
    turtle.left(179)
    turtle.circle(20)
    if abs(turtle.pos()) < 1:
        break

turtle.setheading(180)


while True:
    turtle.forward(300)
    turtle.left(179)
    turtle.circle(20)
    if abs(turtle.pos()) < 1:
        break

turtle.setheading(90)


while True:
    turtle.forward(300)
    turtle.left(179)
    turtle.circle(20)
    if abs(turtle.pos()) < 1:
        break


turtle.end_fill()



turtle.getscreen()._root.mainloop()

【问题讨论】:

  • 什么快什么不快?我无法从问题中弄清楚。
  • 请注意,turtle 不是绘图库。它是一种教育工具。并不意味着要快。
  • 当我运行你的代码时,我并没有真正注意到它变慢了。无论如何,我建议您在您已经拥有的turtle.speed("fastest") 调用之后立即添加对turtle.hideturtle() 的调用,因为正如documentation 所说,“......隐藏海龟可显着加快绘图速度”。

标签: python performance turtle-graphics


【解决方案1】:

我的分析是,您的填充,即turtle.begin_fill()turtle.end_fill(),正在减慢代码 3X 的速度,没有实际效果。其中一张是填充,一张是没有

如果您无法欣赏差异(即使是全尺寸),那么填充可能只是浪费时间。如果您只想要最终图像,而不关心观看它的绘制,那么为了获得更高的性能,我建议:

from turtle import Screen, Turtle

screen = Screen()
screen.bgcolor("Red")
screen.tracer(False)

turtle = Turtle(visible=False)
turtle.color("Yellow", "Pink")

for heading in range(0, 360, 90):

    turtle.setheading(heading)

    turtle.begin_fill()

    while True:
        turtle.forward(300)
        turtle.left(179)
        turtle.circle(20)
        if abs(turtle.pos()) < 1:
            break

    turtle.end_fill()

screen.tracer(True)
screen.mainloop()

【讨论】:

  • 谢谢!没有意识到是动画让它慢了这么多