属性错误: 'AxesSubplot' 对象没有 'Circle' 属性。如何在 tkinter 中嵌入 matplotlib?

3

我正在尝试将一个轨道模拟嵌入到一个tkinter框架中,我已经成功地让图形绘制出来了,现在我只是想在图形中输入圆圈以代表行星。我已经寻找了FigureCanvasTkAgg如何绘制圆的文档,但没有找到任何有用的信息,希望有人能够帮助。

以下是代码:

matplotlib.use('TkAgg')
root = Tk.Tk()
root.wm_title("Orbital Simulation")
fig = plt.Figure()
canvas = FigureCanvasTkAgg(fig, root)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

ax=fig.add_subplot(111)
fig.subplots_adjust(bottom=0.25)

gridArea = [0, 200, 0, 200]  # margins of the coordinate grid
ax.axis(gridArea)  # create new coordinate grid
ax.grid(b="on")  # place grid

.    
.
.

def placeObject(self):
    drawObject = ax.Circle(self.position, radius=self.radius, fill=False, color="black")
    ax.gca().add_patch(drawObject)
    ax.show()

错误:

drawObject = ax.Circle(self.position, radius=self.radius, fill=False, color="black") AttributeError: 'AxesSubplot' 对象没有 'Circle' 属性

非常感谢任何帮助。


请同时发布完整的错误代码。 - Delrius Euphoria
这是完整的错误代码。 - ben green
1个回答

1

Axes实例没有Circle方法。那是matplotlib.patches的一部分,可以单独导入。

此外,当您将补丁添加到ax时,您不需要执行ax.gca(),因为您已经有一个当前Axes的句柄(即不需要.gca(),它代表获取当前轴)。

最后,Axes没有show()方法。那是pyplot模块中的一个函数,可以调用plt.show()

如果您还没有,请添加以下导入:

import matplotlib.pyplot as plt
from matplotlib.patches import Circle
然后修改您的函数为:
def placeObject(self):
    drawObject = Circle(self.position, radius=self.radius, fill=False, color="black")
    ax.add_patch(drawObject)
    plt.show()


不用客气。您不应该编辑问题中的代码:未来的读者将无法看到问题所在以及答案如何帮助解决问题! - tmdavison

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,