更新动画变量

2024-06-01 21:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图写一个程序来模拟两个天体的轨道。我已经能够创建两个天体轨道的动画,并试图在动画的上角添加一个计数器来显示系统的动能

我将动能存储在一个名为“ke”的列表中,并希望动画显示列表中对应于物体位置的值

然而,当我试图编写显示动能所需的代码时,我必须返回变量“energy\u text”,但我得到一个错误:AttributeError:“list”对象没有属性“set\u animated”

如何正确返回/更新变量?

fig = plt.figure()
ax = plt.axes()
ax = plt.axes(xlim=(-12*10**6, 12*10**6), ylim=(-12*10**6, 12*10**6))
patches = []
patches.append(plt.Circle((r_phobos_h[0][0],r_phobos_h[0][1]),5*10**5,color="b", animated=True))
patches.append(plt.Circle((r_mars_h[0][0],r_mars_h[0][1]),5*10**6,color="orange", animated=True))

energy_text = ax.text(0.02, 0.90, '', transform=ax.transAxes)
def init():
    for i in range(0, len(patches)):
            ax.add_patch(patches[i])
    energy_text.set_text('')
    return patches, energy_text

def animate(i):
    patches[0].center = (r_phobos_h[i][0], r_phobos_h[i][1])
    patches[1].center = (r_mars_h[i][0], r_mars_h[i][1])
    energy_text.set_text(ke[i])
    return patches, energy_text

numframes = len(t)
anim = FuncAnimation(fig, animate, init_func=init, frames = numframes, interval=0.01,blit=True)

plt.show()

Tags: texttrueinit动画pltax天体energy
1条回答
网友
1楼 · 发布于 2024-06-01 21:24:15

通过写入return patches, energy_text,您不会将平面列表返回给animation。 通过将行更改为return patches + [energy_text],它应该可以工作:

return patches, energy_text    # -> [[patch_a, patch_b, ...patch_n], text1]
return patches + [energy_text] # -> [patch_a, patch_b, ...patch_n, text1]

相关问题 更多 >