Skip to content

Commit 86f6cb3

Browse files
committed
Warn when trying to start a GUI event loop out of the main thread.
1 parent 5a3b32f commit 86f6cb3

File tree

1 file changed

+21
-2
lines changed

1 file changed

+21
-2
lines changed

lib/matplotlib/pyplot.py

Lines changed: 21 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
@@ -177,6 +181,12 @@ def findobj(o=None, match=None, include_self=True):
177181
return o.findobj(match, include_self=include_self)
178182

179183

184+
def _get_required_interactive_framework():
185+
global _backend_mod
186+
return getattr(
187+
_backend_mod.FigureCanvas, "required_interactive_framework", None)
188+
189+
180190
def switch_backend(newbackend):
181191
"""
182192
Close all open figures and set the Matplotlib backend.
@@ -222,8 +232,7 @@ class _backend_mod(matplotlib.backend_bases._Backend):
222232
_log.debug("Loaded backend %s version %s.",
223233
newbackend, _backend_mod.backend_version)
224234

225-
required_framework = getattr(
226-
_backend_mod.FigureCanvas, "required_interactive_framework", None)
235+
required_framework = _get_required_interactive_framework()
227236
if required_framework is not None:
228237
current_framework = cbook._get_running_interactive_framework()
229238
if (current_framework and required_framework
@@ -244,9 +253,18 @@ class _backend_mod(matplotlib.backend_bases._Backend):
244253
matplotlib.backends.backend = newbackend
245254

246255

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

252270

@@ -275,6 +293,7 @@ def show(*args, **kwargs):
275293
override the blocking behavior described above.
276294
"""
277295
global _backend_mod
296+
_warn_if_gui_out_of_main_thread()
278297
return _backend_mod.show(*args, **kwargs)
279298

280299

0 commit comments

Comments
 (0)