类型错误: 'Circle'对象不支持索引



我正在研究一个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

整个回溯如下:

Traceback (most recent call last):
  File "SolarSystem4.py", line 145, in <module> SolarSystem.run()
  File "SolarSystem4.py", line 132, in run ax.add_patch(self.patches[q])
  File      "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 1562, in add_patch
self._update_patch_limits(p)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/axes.py", line 1580, in _update_patch_limits
xys = patch.get_patch_transform().transform(vertices)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/patches.py", line 1256, in get_patch_transform
self._recompute_transform()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/matplotlib/patches.py", line 1240, in _recompute_transform
center = (self.convert_xunits(self.center[0]),
TypeError: 'Circle' object does not support indexing

看起来问题出在 run 函数的 for 循环内的第一行。 这里:

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

您正在构造一个 Circle 对象,然后将该对象作为第一个参数传递给另一个Circle对象的构造函数。 Circle.__init__的第一个参数是圆中心的xy坐标。因此,当您创建第二个Circle时,它期望(x,y)形式的元组作为第一个参数,而是获取一个完整的Circle对象,因此它最终得到一个属性,如下所示:

self.center = Circle(....)

而不是

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

这不会导致任何问题,直到调用尝试为该self.center属性编制索引的 _recompute_transform 方法。 索引元组没有问题,但它无法索引Circle因此会引发错误。 要解决此问题,请将有问题的行更改为:

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

换句话说,一次只做一个Circle,并为其__init__方法提供它期望的参数。

最新更新