首页 > 解决方案 > 如何快速撤消海龟?

问题描述

我正在制作一个创建螺旋计的程序。这是我的代码:

from turtle import *
from random import randint
speed(10000)
for i in range(20):
    col = randint(1, 5)
    if col == 1:
        pencolor("orange")
    elif col == 2:
        pencolor("blue")
    elif col == 3:
        pencolor("green")
    elif col == 4:
        pencolor("purple")
    elif col == 5:
        pencolor("dark blue")
    circle(50)
    left(20)

while undobufferentries():
    undo()

但是,程序的最后一部分是问题。我希望这部分,即撤消,非常快,就像创建螺旋一样快。如何快速撤消?

标签: pythonpython-3.xturtle-graphics

解决方案


三遍你说你想要它“非常快”,但你也说,“就像创造螺旋一样快”。我们可以轻松地让它比创建 spiro 的速度更快,但只需稍微多做一些工作以使其“尽可能快”。

这个问题指出了undo()机制的弱点。要撤消您的一个圈子,需要执行 80 多个步骤。但是,即使这样也不能完全清楚为什么它这么慢。如果我们关闭屏幕更新,我们可以让它即时更新。但如果这是可以接受的,那么你不妨替换undo()clear().

我很少鼓励人们弄乱tracer(),即使我这样做了,我通常也会写一些简单的示例tracer(False)tracer(True),以避免使用数字参数。但这是我们想要一个特定的数字参数tracer()来控制undo()图形速度的罕见情况:

from turtle import *
from random import choice

COLORS = ["orange", "blue", "green", "purple", "dark blue"]

hideturtle()
speed('fastest')

for _ in range(20):
    pencolor(choice(COLORS))
    circle(50)
    left(20)

tracer(20)  # value unrelated to either 20 above
while undobufferentries() > 1:
    undo()  # undo everything but hideturtle()
tracer(1)

exitonclick()

在我的系统上,绘图的撤消现在与do的速度相同,但您可能需要微调参数以tracer()达到您想要的效果。


推荐阅读