Skip to content

Commit 5062e9f

Browse files
committed
Warn when trying to start a GUI event loop out of the main thread.
1 parent 268d498 commit 5062e9f

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

lib/matplotlib/pyplot.py

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@
2626
import re
2727
import sys
2828
import time
29+
try:
30+
import threading
31+
except ImportError:
32+
import dummy_threading as threading
2933

3034
from cycler import cycler
3135
import matplotlib
@@ -175,6 +179,11 @@ def findobj(o=None, match=None, include_self=True):
175179
return o.findobj(match, include_self=include_self)
176180

177181

182+
def _get_required_interactive_framework(backend_mod):
183+
return getattr(
184+
backend_mod.FigureCanvas, "required_interactive_framework", None)
185+
186+
178187
def switch_backend(newbackend):
179188
"""
180189
Close all open figures and set the Matplotlib backend.
@@ -217,8 +226,7 @@ def switch_backend(newbackend):
217226
class backend_mod(matplotlib.backend_bases._Backend):
218227
locals().update(vars(importlib.import_module(backend_name)))
219228

220-
required_framework = getattr(
221-
backend_mod.FigureCanvas, "required_interactive_framework", None)
229+
required_framework = _get_required_interactive_framework(backend_mod)
222230
if required_framework is not None:
223231
current_framework = cbook._get_running_interactive_framework()
224232
if (current_framework and required_framework
@@ -242,8 +250,17 @@ class backend_mod(matplotlib.backend_bases._Backend):
242250
matplotlib.backends.backend = newbackend
243251

244252

253+
def _warn_if_gui_out_of_main_thread():
254+
if (_get_required_interactive_framework(_backend_mod)
255+
and threading.current_thread() is not threading.main_thread()):
256+
cbook._warn_external(
257+
"Starting a Matplotlib GUI outside of the main thread will likely "
258+
"fail.")
259+
260+
245261
def new_figure_manager(*args, **kwargs):
246262
"""Create a new figure manager instance."""
263+
_warn_if_gui_out_of_main_thread()
247264
return _backend_mod.new_figure_manager(*args, **kwargs)
248265

249266

@@ -270,6 +287,7 @@ def show(*args, **kwargs):
270287
This is experimental, and may be set to ``True`` or ``False`` to
271288
override the blocking behavior described above.
272289
"""
290+
_warn_if_gui_out_of_main_thread()
273291
return _backend_mod.show(*args, **kwargs)
274292

275293

0 commit comments

Comments
 (0)