首页 > 解决方案 > plt.show 不在另一个线程上工作,仅在主线程上

问题描述

我正在尝试编写一个 python 脚本来读取 CSV 文件并生成一个带有 GUI 界面图形的 PNG 文件。代码如下:

from matplotlib import peplos as plot
from tkinter.constants import LEFT, RIGHT, S
import tkinter as tk, time, threading, random, queue

class GuiPart(object):
    def __init__(self, master, queue, client_instance):
        self.queue = queue
        self.button1 =  tk.Button(master, text="Command", padx=10, 
                        pady=5, fg="white", bg="#263D42",   command=client_instance.start_thread1)

    self.button1.pack()

    def processIncoming(self):
        while self.queue.qsize():
            pass

class ThreadedClient(object):

    def __init__(self, master):
   
        self.master = master
   
        self.queue = queue.Queue()
        self.running = True

    
        self.gui = GuiPart(master, self.queue, self)
    
        self.periodic_call()

    
    def start_thread1(self):
    
        thread1 = threading.Thread(target=self.worker_thread1)
        thread1.start()

    def periodic_call(self):
        self.master.after(200, self.periodic_call)
        self.gui.processIncoming()
        if not self.running:
            import sys
            sys.exit(1)

    def worker_thread1(self):

   
        if self.running:
   
    
            time.sleep(rand.random() * 1.5)

            x = [1, 2, 3, 4]
            y = [4, 3, 2, 1]

            plt.plot(x, y)
            plt.show()

    def end_application(self):
         self.running = False

rand = random.Random()
root = tk.Tk()
client = ThreadedClient(root)
root.mainloop()

我还没有完全展示如何阅读 CSV,所有的绘图,但只展示了问题所在。我选择这种方法是因为我不希望 GUI 因大型 CSV 文件而冻结。我现在面临的问题是如果我想做 plt.show() 而不是告诉我我在主线程中。我试图在主线程中移动它,但冻结问题会再次出现。我还尝试在主线程和另一个线程中添加 Toplevel,但没有任何成功。任何帮助将非常感激。

编辑:我已经阅读了更多关于这个问题的信息,它似乎是一个 Tkinter 问题,而不是一个 matplotlib 问题。那么是否可以在工作线程和 plt.show 中仅在主线程中执行所有操作?如果是的话,有人可以告诉我怎么做吗?我试图找到答案很多天......谢谢!

标签: pythonmultithreadingmatplotlibtkinter

解决方案


推荐阅读