Matplotlib and :RuntimeError: main thread is not in main loop: Matplotlib and :RuntimeError: main thread is not in main loop: tkinter tkinter

Matplotlib and :RuntimeError: main thread is not in main loop:


As seen here, have you tried adding the following code to the top of your imports?

import matplotlibmatplotlib.use('Agg')import matplotlib.pyplot as plt


matplotlib uses TkAgg for default. Backends like TkAgg, FltkAgg, GTK, GTKAgg, GTKCairo, Wx, and WxAgg are all GUI based. And most GUI backends require being run from the main thread. Thus, if you are running on an environment without GUI, it will throw RuntimeError: main thread is not in main loop.

Therefore, just switch to backends that do not use GUI: Agg, Cairo, PS, PDF, or SVG.

For example:

import matplotlib.pyplot as pltplt.switch_backend('agg')

References: https://matplotlib.org/stable/faq/howto_faq.html#work-with-threads