在拖曳位置使用图形的相同实例时删除图形

时间:2019-04-17 07:44:08

标签: python matplotlib

在下面的代码中,我在两个帧中渲染相同的图形。首先,当鼠标悬停在其上时,我添加一个注释。第二个只是我在不同的框架中显示图形。问题是,当我再次将鼠标悬停在第一个图形上时,它给了我这个错误“ RuntimeError:FigureCanvasWxAgg类型的包装的C / C ++对象已被删除”

 import wx

import matplotlib
matplotlib.interactive(True)
matplotlib.use('WXAgg')
from matplotlib.figure import Figure
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas

import numpy as np

class GrpahGenerator:
    def generate_Graph(self):
        self.figure = Figure(figsize=(6, 4), dpi=100)
        self.axes = self.figure.add_subplot(111)
        self.axes.bar(range(10), 20 * np.random.rand(10))
        return self.figure

class Frame2(wx.Frame):
    def __init__(self, title,fig):
        wx.Frame.__init__(self, None, title=title, pos=(150,150), size=(800,600))
        self.figure1=fig
        self.panel = wx.Panel(self)
        self.canvas = FigureCanvas(self.panel, wx.ID_ANY, self.figure1)

class Frame(wx.Frame):
    def __init__(self, title,fig):
        wx.Frame.__init__(self, None, title=title, pos=(150,150), size=(800,600))


        self.figure=fig
        self.panel = wx.Panel(self)
        saveButton = wx.Button(self.panel, label='generate', pos=(50, 5), size=(80, 25))
        saveButton.Bind(wx.EVT_BUTTON, self.OnButtonClick)
        self.canvas = FigureCanvas(self.panel, wx.ID_ANY, self.figure)

        for ax in self.figure.axes:
            self.annot = ax.annotate("", xy=(0, 0), xytext=(-20, 20), textcoords="offset points",
                                     bbox=dict(boxstyle="round", fc="black", ec="b", lw=2),
                                     )

        self.canvas.figure.canvas.mpl_connect('motion_notify_event', self.on_motion)
    def OnButtonClick(self,event):
        # figure1=GrpahGenerator()

        top = Frame2("test",self.figure)
        top.Show()
    def on_motion(self, event):

            vis = self.annot.get_visible()
            axs = event.inaxes

            for i, artist in enumerate(axs.patches):
                con, ind = artist.contains(event)

                if con:

                    self.update_annot(ind, artist, str(artist.get_facecolor()))
                    self.figure.canvas.draw_idle()
                    self.annot.set_visible(True)
                else:
                    if vis:

                        self.figure.canvas.draw_idle()
    def update_annot(self, ind,artist, text):
        x, y = artist.xy
        self.annot.xy = (x, y)
        self.annot.set_text(text)
        self.annot.get_bbox_patch().set_alpha(0.4)

app = wx.PySimpleApp()
fig = GrpahGenerator()
figure=fig.generate_Graph()
top = Frame("test",figure)
top.Show()
app.MainLoop()

当我更改按钮的回调函数以生成新实例时  这样的图,一切正常

    def OnButtonClick(self,event):
     figure1=GrpahGenerator()

     top = Frame2("test",figure1.generate_Graph())
     top.Show()

我的意图是我不想再次绘制图形,因为我的真实图形   需要很长时间才能生成,并且冻结了GUI

0 个答案:

没有答案