如何使用Turtle图形模块同步动画



我已经编写了以下Python代码,以创建使用Python Turtle的旋转图的动画。我面临的问题是,动画无法正确同步。我不想向人们展示东西的旋转方式。因此,我必须小心地选择turtle.tracer命令中的帧速率。好吧,如果您仔细观察,r的每个值都会产生旋转,因此我必须在每个r末尾更新屏幕。对于r的每个值,r的循环内部都有1202个迭代。但这不会产生所需的效果。

我该怎么做才能纠正这个?

import turtle
import math
am = turtle
am.ht()
am.tracer(1202,0)
for r in range(0,600):
    #axes
    am.pu()
    am.setpos(0,500)
    am.pd()
    am.setpos(0,-500)
    am.pu()
    am.setpos(-650,0)
    am.pd()
    am.setpos(0,0)
    am.write("0",align="right",font=("Times New Roman",14,"normal"))
    am.setpos(650,0)
    am.pu()
    am.setpos(-300*math.cos(r*math.pi/100),300*math.sin(r*math.pi/100))
    am.pd()
    #axes
    am.pencolor("red")
    for x in range(-300,301):
        g=math.sin(x)
        t=math.cos(x)
        y =100*g*t*math.sin(2*(x**2)*math.pi/100)
        am.setpos(x*math.cos(r*math.pi/100)+y*math.sin(r*math.pi/100),-x*math.sin(r*math.pi/100)+y*math.cos(r*math.pi/100))
    #if(x%4==0):
       #am.write(x)
    am.pu()
    am.setpos(-300*math.sin(r*math.pi/100),-300*math.cos(r*math.pi/100))
    am.pd()
    am.pencolor("blue")
    for y in range(-300,301):
        c=math.sin(y)
        d=math.cos(y)
        x =100*c*d*math.cos(2*(y**2)*math.pi/100)
        am.setpos(x*math.cos(r*math.pi/100)+y*math.sin(r*math.pi/100),-x*math.sin(r*math.pi/100)+y*math.cos(r*math.pi/100))
    am.reset()
am.exitonclick()

我相信以下内容会做您想要的。当您准备向用户展示某些内容时,我将示踪剂逻辑更改为使用显式.update()的手册。我还将轴图与主循环分开,因为我们真的不需要每次清除并重新绘制它:

import math
from turtle import Turtle, Screen
screen = Screen()
screen.tracer(0)
# axes
axes = Turtle(visible=False)
axes.pu()
axes.setpos(0, 500)
axes.pd()
axes.setpos(0, -500)
axes.pu()
axes.setpos(-650, 0)
axes.pd()
axes.setpos(0, 0)
axes.write("0", align="right", font=("Times New Roman", 14, "normal"))
axes.setpos(650, 0)
am = Turtle(visible=False)
for r in range(0, 600):
    am.pu()
    am.setpos(-300 * math.cos(r * math.pi / 100), 300 * math.sin(r * math.pi / 100))
    am.pd()
    am.pencolor("red")
    for x in range(-300, 301):
        g = math.sin(x)
        t = math.cos(x)
        y = 100 * g * t * math.sin(2 * x**2 * math.pi / 100)
        am.setpos(x * math.cos(r * math.pi / 100) + y * math.sin(r * math.pi / 100), -x * math.sin(r * math.pi / 100) + y * math.cos(r * math.pi / 100))
    am.pu()
    am.setpos(-300 * math.sin(r * math.pi / 100), -300 * math.cos(r * math.pi / 100))
    am.pd()
    am.pencolor("blue")
    for y in range(-300, 301):
        c = math.sin(y)
        d = math.cos(y)
        x = 100 * c * d * math.cos(2 * y**2 * math.pi / 100)
        am.setpos(x * math.cos(r * math.pi / 100) + y * math.sin(r * math.pi / 100), -x * math.sin(r * math.pi / 100) + y * math.cos(r * math.pi / 100))
    screen.update()
    am.reset()
    am.hideturtle()  # made visible by reset()
screen.exitonclick()

最后,这可能是一个错误:

am = turtle

并且不做您认为的事情(模块名称别名,而不是实际的乌龟。)

最新更新