TypeError:“Circle”对象不支持索引

2024-04-26 07:35:40 发布

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

我正在编写一个python代码来模拟任何给定系统的轨道运动。我使用FuncAnimation来设置一些圆的位置的动画。问题是我试图使它尽可能的通用,所以我认为一个数组有不同的补丁,我在每一帧更新,是一个好主意。但是每次我运行它时都会遇到这个错误:TypeError: 'Circle' object does not support indexing

以下是动画的部分代码:

# This class method is the core of the animation and how the different CelestialBodies interact.
def Animation(self,a):
    for u in range(len(self.system)-1):
        self.system[u].Position(self.system)
        self.patches[u].center = (self.system[u].P[-1][0],self.system[u].P[-1][1])
    return self.patches

# This is the main class method, which combines the rest of methods to run the animation.
def run(self):
    # Create the axes for the animation
    fig = plt.figure()
    ax = plt.axes()
    ax.axis('scaled')
    ax.set_xlim(-self.max, self.max)
    ax.set_ylim(-self.max, self.max)

    # Create the patches and add them to the axes
    self.patches = []
    for q in range(len(self.system)-1):
        self.patches.append(plt.Circle(plt.Circle((0,0), 695700000, color='black')))
        ax.add_patch(self.patches[q])
    # Call the animation and display the plot
    anim = FuncAnimation(fig, self.Animation, init_func=self.init, frames=10, repeat=True, interval=1, blit=False)
    plt.title("Solar System - Numerical Intregation Simulation")
    plt.xlabel("Position in x (m)")
    plt.ylabel("Position in y (m)")
    plt.grid()
    plt.show()
# Constructor for the animation
def init(self):
    return self.patches

整个回溯过程如下:

^{pr2}$

Tags: andtheinselffordefpositionplt
1条回答
网友
1楼 · 发布于 2024-04-26 07:35:40

问题似乎出在run函数中for循环内的第一行。这里:

self.patches.append(plt.Circle(plt.Circle((0,0), 695700000, color='black')))

您正在构造一个Circle对象,然后将该对象作为第一个参数传递给另一个Circle对象的构造函数。Circle.__init__的第一个参数是圆中心的xy坐标。因此,当您创建第二个Circle时,它需要一个格式为(x,y)的元组作为第一个参数,但是它得到了一个完整的Circle对象,因此它最终得到了一个类似于:

^{pr2}$

而不是

self.center = (0,0)  # or some other coordinates

在调用_recompute_transform方法并尝试索引self.center属性之前,这不会引起任何问题。索引元组没有问题,但是它不能索引Circle,因此会抛出一个错误。要修复,请将有问题的行更改为:

self.patches.append(plt.Circle((0,0), 695700000, color='black'))

换句话说,一次只生成一个Circle,并给它的__init__方法提供它期望的参数。在

相关问题 更多 >