首页 > 解决方案 > python GUI中的TypeError matplotlib

问题描述

我正在开发一个带有由 Qt5 编写的 GUI 的 python 代码。GUI 已经包含一个 2D 绘图。我想在新窗口中打开一个图来绘制一些东西。使用 matplotlib.pyplot.figure 会产生错误。这是生成绘图的函数:

def deformed_mesh_3D(model, scale):
    x, y = model.nodal_coordinates
    z = list()
    z_reference = list()
    for node in model.nodes:
        if node.results.get('w') is None:
            return
        z.append(node.results.get('w')*scale)
        z_reference.append(0.0)

    triangles = list()
    for element in model.elements:
        if type(element)==QuadPlateBending:
            index1 = element.nodes[0].id - 1
            index2 = element.nodes[1].id - 1
            index3 = element.nodes[2].id - 1
            index4 = element.nodes[3].id - 1
            triangles.append([index1, index2, index3])
            triangles.append([index1, index3, index4])
    triangulation = tri.Triangulation(x, y, triangles)

    fig = plt.figure(FigureClass=Figure)
    ax = fig.add_subplot(111, projection='3d')
    ax.plot_trisurf(triangulation, z, cmap='jet')
    ax.plot_trisurf(triangulation, z_reference, alpha=0.33, color='grey')
    ax.axis('equal')
    ax.margins(0.1)
    ax.invert_xaxis()
    ax.invert_yaxis()
    ax.set(xlabel='< X >', ylabel='< Y >', zlabel='< Z >')
    plt.show()

这会产生以下错误。

File "D:\Programs\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 525, in figure
**kwargs)
File "D:\Programs\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 3218, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "D:\Programs\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 3224, in new_figure_manager_given_figure
canvas = cls.FigureCanvas(figure)
TypeError: 'NoneType' object is not callable

更新:经过一些广泛的调试,问题原来与后端有关。GUI 中使用的后端是 Qt5Agg,由于某种原因,当使用外部绘图时,它会给出上述错误。我试过plt.switch_backend('TkAgg')了,它给出了一个导入错误。我从 pyplot 的源代码(此处)中注释掉了引发此错误的行。显然,这样做不是一个好主意,但它已经成功地产生了情节窗口。有没有办法将后端从“Qt5Agg”动态切换到“TkAgg”?

标签: pythonuser-interfacematplotlib

解决方案


根据文档 FigureClass参数应该是Figure. 默认情况下它将使用Figure,因此无需指定。我认为这将解决错误。


推荐阅读