How to speed up python's 'turtle' function and stop it freezing at the end

后端 未结 4 1830
后悔当初
后悔当初 2020-12-05 14:13

I have written a turtle program in python, but there are two problems.

  1. It goes way too slow for larger numbers, I was wonder how I can speed up turtle.
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 14:35

    Python turtle goes very slowly because screen refreshes are performed after every modification is made to a turtle.

    You can disable screen refreshing until all the work is done, then paint the screen, it will eliminate the millisecond delays as the screen furiously tries to update the screen from every turtle change.

    For example:

    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)
    

    This code makes a thousand turtles at random locations, and displays the picture in about 200 milliseconds.

    Had you not disabled screen refreshing with turtle.tracer(0, 0) command, it would have taken several minutes as it tries to refresh the screen 3000 times.

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

提交回复
热议问题