python - 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 中仅在主线程中执行所有操作?如果是的话,有人可以告诉我怎么做吗?我试图找到答案很多天......谢谢!
解决方案
推荐阅读
- mongodb - 副本集重新配置在 mongo 中不起作用
- javascript - lodash.differenceBy 在香草 JavaScript 中?
- python - Scipy稀疏矩阵行广播
- cucumber - 是否可以从 JSON 文件传递 Cucumber 功能中的参数值?
- reactjs - ReactNative Redux 导航道具未更新
- java - 改造 2 类文件问题
- html - 如何在reactjs中将插入符号位置放在contentEditable div的末尾?
- scala - 将 scala 数据帧转换为具有数组类型列的数据集
- c# - 实体框架核心闭表(代码优先)
- kotlin - 在有改造的条件下,在 URL 的路径中添加一个参数