Skip to content

fix FigureManagerTk close behavior if embedded in Tk App #17802

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions lib/matplotlib/backends/_backend_tk.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,8 @@ class FigureManagerTk(FigureManagerBase):
The tk.Window
"""

_owns_mainloop = False

def __init__(self, canvas, num, window):
FigureManagerBase.__init__(self, canvas, num)
self.window = window
Expand Down Expand Up @@ -460,7 +462,7 @@ def destroy(self, *args):
self.canvas._tkcanvas.after_cancel(self.canvas._idle_callback)
self.window.destroy()
if Gcf.get_num_fig_managers() == 0:
if self.window is not None:
if self.window is not None and self._owns_mainloop:
self.window.quit()
self.window = None

Expand Down Expand Up @@ -879,8 +881,10 @@ def new_figure_manager_given_figure(cls, num, figure):
def trigger_manager_draw(manager):
manager.show()

@staticmethod
def mainloop():
@classmethod
def mainloop(cls):
managers = Gcf.get_all_fig_managers()
if managers:
cls._owns_mainloop = True
managers[0].window.mainloop()
cls._owns_mainloop = False
3 changes: 2 additions & 1 deletion lib/matplotlib/cbook/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,10 @@ def _get_running_interactive_framework():
return "wx"
tkinter = sys.modules.get("tkinter")
if tkinter:
codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
for frame in sys._current_frames().values():
while frame:
if frame.f_code == tkinter.mainloop.__code__:
if frame.f_code in codes:
return "tk"
frame = frame.f_back
if 'matplotlib.backends._macosx' in sys.modules:
Expand Down
23 changes: 23 additions & 0 deletions lib/matplotlib/tests/test_backend_tk.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import tkinter

import pytest
import numpy as np
from matplotlib import pyplot as plt
Expand Down Expand Up @@ -26,3 +28,24 @@ def evil_blit(photoimage, aggimage, offsets, bboxptr):
np.ones((4, 4, 4)),
(0, 1, 2, 3),
bad_boxes)


@pytest.mark.backend('TkAgg', skip_on_importerror=True)
def test_figuremanager_preserves_host_mainloop():
success = False
def do_plot():
plt.figure()
plt.plot([1,2],[3,5])
plt.close()
root.after(0, legitmate_quit)

def legitmate_quit():
root.quit()
nonlocal success
success = True

root = tkinter.Tk()
root.after(0, do_plot)
root.mainloop()

assert success