Plotting with matplotlib in threads

前端 未结 2 1159
忘掉有多难
忘掉有多难 2020-12-16 15:30

I know there are quite some questions on matplotlib and threading, also that pyplot is not threadsave. I couldn\'t find anything on this particular problem however. What I w

2条回答
  •  死守一世寂寞
    2020-12-16 16:16

    Use a Qt signal to call your plotting function in the main thread

    import matplotlib
    matplotlib.use("qt4agg")
    import matplotlib.pyplot as plt
    import threading
    import time
    
    from PyQt4 import QtCore
    
    class Call_in_QT_main_loop(QtCore.QObject):
        signal = QtCore.pyqtSignal()
    
        def __init__(self, func):
            super().__init__()
            self.func = func
            self.args = list()
            self.kwargs = dict()
            self.signal.connect(self._target)
    
        def _target(self):
            self.func(*self.args, **self.kwargs)
    
        def __call__(self, *args, **kwargs):
            self.args = args
            self.kwargs = kwargs
            self.signal.emit()
    
    @Call_in_QT_main_loop
    def plot_a_graph():
        f,a = plt.subplots(1)
        line = plt.plot(range(10))
        plt.show()
        print("plotted graph")
        print(threading.current_thread())  # print the thread that runs this code
    
    def worker():
        plot_a_graph()
        print(threading.current_thread())  # print the thread that runs this code
        time.sleep(4)
    
    testthread = threading.Thread(target=worker)
    
    testthread.start()
    

提交回复
热议问题