如何加速python的'乌龟'功能并最终阻止它冻结

cli*_*nMe 19 python graphics draw turtle-graphics

我在python中编写了一个海龟程序,但有两个问题.

  1. 对于较大的数字来说,它太慢了,我很想知道如何加速龟.
  2. 它完成后点击时会冻结,说"没有回复"

到目前为止这是我的代码:

import turtle

#Takes user input to decide how many squares are needed
f=int(input("How many squares do you want?"))
c=int(input("What colour would you like? red = 1, blue = 2 and green =3"))
n=int(input("What background colour would you like? red = 1, blue = 2 and green =3"))

i=1

x=65

#Draws the desired number of squares.
while i < f:
    i=i+1
    x=x*1.05
    print ("minimise this window ASAP")
    if c==1:
        turtle.pencolor("red")
    elif c==2:
        turtle.pencolor("blue")
    elif c==3:
        turtle.pencolor("green")
    else:
        turtle.pencolor("black")
    if n==1:
        turtle.fillcolor("red")
    elif n==2:
        turtle.fillcolor("blue")
    elif n==3:
        turtle.fillcolor("green")
    else:
        turtle.fillcolor("white")
    turtle.bk(x)
    turtle.rt(90)
    turtle.bk(x)
    turtle.rt(90)
    turtle.bk(x)
    turtle.rt(90)
    turtle.bk(x)
    turtle.rt(90)
    turtle.up()
    turtle.rt(9)
    turtle.down()
Run Code Online (Sandbox Code Playgroud)

顺便说一句:我在3.2版本!

kal*_*nik 35

  1. turtle.speed设置为最快.
  2. 使用该turtle.speed()功能无需刷新屏幕即可完成工作.
  3. 禁用屏幕刷新fastest然后在最后做turtle.mainloop()

  • 如果您使用较新版本的turtle滚动,则龟对象没有跟踪器属性.您必须为Screen对象设置tracer属性. (3认同)

Eri*_*ski 12

Python龟的速度非常慢,因为在对乌龟进行每次修改后都会执行屏幕刷新.

您可以禁用屏幕刷新,直到所有工作完成,然后绘制屏幕,​​它将消除毫秒延迟,因为屏幕疯狂地尝试从每次更改龟更新屏幕.

例如:

import turtle
import random
import time
screen = turtle.Screen()

turtlepower = []

turtle.tracer(0, 0)
for i in range(1000):
    t = turtle.Turtle()
    t.goto(random.random()*500, random.random()*1000)
    turtlepower.append(t)

for i in range(1000):
    turtle.stamp()

turtle.update()

time.sleep(3)
Run Code Online (Sandbox Code Playgroud)

这段代码在随机位置制作了一千只海龟,并在大约200毫秒内显示图片.

如果你没有用turtle.tracer(0, 0)命令禁用屏幕刷新,它会花费几分钟,因为它试图刷新屏幕3000次.

https://docs.python.org/2/library/turtle.html#turtle.delay