I am trying to write a python script that reads a CSV file and generates a PNG file with some graphs with GUI interface. The code is below:
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()
I haven't shown the all way how to read the CSV, all the plotting, but only where the issue is. I am choosing this approach as with I don't want the GUI to freeze with large CSV files. To problem that I am facing now is if I want to do plt.show() instead will not work telling me I am in the main thread. I tried to move it in the main thread but the freezing issue will reappear. I have also tried to add Toplevel both in main and in another thread without any success. Any help would be much appreciated.
Edit: I have read more about the issue and it seems it is a Tkinter problem and not a matplotlib one. Would it be possble then to do all the operations in the worker thread and the plt.show only in the main thread? If yes, can someone show me how to that? I have tried to find an answer for many days... thank you!