diff --git a/lib/matplotlib/_pylab_helpers.py b/lib/matplotlib/_pylab_helpers.py index 26ba7a171244..27904dd84b6f 100644 --- a/lib/matplotlib/_pylab_helpers.py +++ b/lib/matplotlib/_pylab_helpers.py @@ -53,18 +53,17 @@ def destroy(cls, num): It is recommended to pass a manager instance, to avoid confusion when two managers share the same number. """ - if all(hasattr(num, attr) for attr in ["num", "_cidgcf", "destroy"]): + if all(hasattr(num, attr) for attr in ["num", "destroy"]): manager = num if cls.figs.get(manager.num) is manager: cls.figs.pop(manager.num) - else: - return else: try: manager = cls.figs.pop(num) except KeyError: return - manager.canvas.mpl_disconnect(manager._cidgcf) + if hasattr(manager, "_cidgcf"): + manager.canvas.mpl_disconnect(manager._cidgcf) manager.destroy() gc.collect(1) diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index fe8cc66913cc..816db303ff65 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -3294,8 +3294,8 @@ def _update_view(self): def configure_subplots(self, *args): plt = _safe_pyplot_import() - tool = plt.subplot_tool(self.canvas.figure) - tool.figure.canvas.manager.show() + self.subplot_tool = plt.subplot_tool(self.canvas.figure) + self.subplot_tool.figure.canvas.manager.show() def save_figure(self, *args): """Save the current figure.""" diff --git a/lib/matplotlib/backends/backend_nbagg.py b/lib/matplotlib/backends/backend_nbagg.py index 9eb076d9ec44..b921aa0a1d6e 100644 --- a/lib/matplotlib/backends/backend_nbagg.py +++ b/lib/matplotlib/backends/backend_nbagg.py @@ -231,7 +231,12 @@ def new_figure_manager_given_figure(num, figure): if is_interactive(): manager.show() figure.canvas.draw_idle() - canvas.mpl_connect('close_event', lambda event: Gcf.destroy(manager)) + + def destroy(event): + canvas.mpl_disconnect(cid) + Gcf.destroy(manager) + + cid = canvas.mpl_connect('close_event', destroy) return manager @staticmethod diff --git a/lib/matplotlib/pyplot.py b/lib/matplotlib/pyplot.py index 18e1739cab6d..73e77f6f0174 100644 --- a/lib/matplotlib/pyplot.py +++ b/lib/matplotlib/pyplot.py @@ -1546,7 +1546,8 @@ def subplot_tool(targetfig=None): """ Launch a subplot tool window for a figure. - A `matplotlib.widgets.SubplotTool` instance is returned. + A `matplotlib.widgets.SubplotTool` instance is returned. You must maintain + a reference to the instance to keep the associated callbacks alive. """ if targetfig is None: targetfig = gcf()