2

I am using TKinter to build a GUI (for a socket connection to a multichannel analyzer) to receive & plot data (~15.000.000 values) in regular intervals (~15 seconds).

While receiving data I don't want the GUI to freeze, so I am using multi-threading for connection handling, data receiving & plotting operations. I accomplished this, as seen in the reproducable code, with setting an event with threading.Event() and handle one thread after another (few lines of code in initSettings() & acquireAndPlotData). The only time I interfere with the GUI is when plotting to the canvas & I do this with tkinters after() method.

When started, the code runs without freezing & receives and plots as long as the window is opened & works as expected.

As I read on handling blocking I/O operations in tkinter GUIs, I only found examples with queuing and checking the queue recursively (with Queue & after(), 1 2 3 4 5 ), but I found it to be way more convenient and easier to handle these operations with threading.Event().

Now my question is:

Am I using the right approach or am I missing something important here? (regarding thread safety, race conditions, what if plotting fails and takes longer than data acquisiton? Something I don't think of? Bad practices? etc...)

I would be really thankful for feedback on this matter!

Reproducable code

#####################*** IMPORTS ***#######################################################
import tkinter
from tkinter import ttk

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure

import time
import threading

import numpy as np

################### *** FUNCTIONS *** #########################################################
# *** initializes two threads for initializing connection & receiving/plotting data ***
def onStartButtonClick(event):
    #
    init_settings_thread.start()
    acquire_and_plot_data_thread.start()
    #

# *** inizialize connection & set event when finished & ready for sending data ***
def initSettings():
    #time.sleep() simulates the time it takes to inizialize the connection
    time.sleep(2)
    start_data_acquisition_event.set()

# *** waiting for event/flag from initSettings() & start data receiving/plotting loop afer event set ***
def acquireAndPlotData():
    start_data_acquisition_event.wait()
    while start_data_acquisition_event.is_set():
        # time.sleep() simulates the time it takes the connection to fill up the buffer
        time.sleep(4)
        # send updateGuiFigure to tkinters event queue, so that it won't freeze
        root.after(0, updateGuiFigure)

# *** set new data points on existing plot & blit GUI canvas ***
def updateGuiFigure():
    # simulate data -> 15.000.000 points in real application
    line.set_xdata(np.random.rand(10))
    #
    line.set_ydata(np.random.rand(10))
    #
    plotting_canvas.restore_region(background)  # restore background
    ax.draw_artist(line)  # redraw just the line -> draw_artist updates axis
    plotting_canvas.blit(ax.bbox)  # fill in the axes rectangle
    #

# *** update background for resize events ***
def update_background(event):
    global background 
    background = plotting_canvas.copy_from_bbox(ax.bbox)

##########################*** MAIN ***#########################################################

# Init GUI
root = tkinter.Tk()

# Init frame & canvas
frame = ttk.Frame(root)
plotting_area = tkinter.Canvas(root, width=700, height=400)
#
frame.grid(row=0, column=1, sticky="n")
plotting_area.grid(row=0, column=0)

# Init button & bind to function onStartButtonClick
start_button = tkinter.Button(frame, text="Start")
start_button.bind("<Button-1>", onStartButtonClick)
start_button.grid(row=0, column=0)

# Init figure & axis
fig = Figure(figsize=(7, 4), dpi=100)
ax = fig.add_subplot(111)

# Connect figure to plotting_area from GUI
plotting_canvas = FigureCanvasTkAgg(fig, master=plotting_area)

# Set axis
ax.set_title('Test')
ax.grid(True)
ax.set_xlabel('x-axis')
ax.set_ylabel('y-axis')
ax.set(xlim=[0,1], ylim=[0, 1])

# Init plot
line, = ax.plot([], [])
# if animated == True: artist (= line) will only be drawn when manually called draw_artist(line)
line.set_animated(True)

# Draw plot to GUI canvas
plotting_canvas.draw()
plotting_canvas.get_tk_widget().pack(fill=tkinter.BOTH)
background = plotting_canvas.copy_from_bbox(ax.bbox)  # cache background
plotting_canvas.mpl_connect('draw_event', update_background)  # update background with 'draw_event'

# Init threads
start_data_acquisition_event = threading.Event()
#
init_settings_thread = threading.Thread(name='init_settings_thread', target=initSettings, daemon=True)
acquire_and_plot_data_thread = threading.Thread(name='acquire_and_plot_data_thread', target=acquireAndPlotData, daemon=True)

# Start tkinter mainloop
root.mainloop()

A code snipped example handled with multiple classes looks like this (same as code above, but not reproducible, can be neglected):

def onStartButtonClick(self):
    #
    .
    # Disable buttons and get widget values here etc.
    .
    #
    self.start_data_acquisition_event = threading.Event()
    self.init_settings_thread = threading.Thread(target=self.initSettings)
    self.acquire_and_plot_data_thread = threading.Thread(target=self.acquireAndPlotData)
    #
    self.init_settings_thread.start()
    self.acquire_and_plot_data_thread.start()
    # FUNCTION END

def initSettings(self):
    self.data_handler.setInitSettings(self.user_settings_dict)
    self.data_handler.initDataAcquisitionObject()
    self.start_data_acquisition_event.set()

def acquireAndPlotData(self):
    self.start_data_acquisition_event.wait()
    while self.start_data_acquisition_event.is_set():
        self.data_handler.getDataFromDataAcquisitionObject()
        self.master.after(0, self.data_plotter.updateGuiFigure)
6
  • "but I found it to be way more convenient and easier to handle these operations with threading.Event()" what kind of benefits are you missing here ? Aug 14, 2020 at 14:20
  • 1
    For me this is more logic & easy to use, than to make a queue class or function and call after() every few moments to check the queue. So I think that I am not missing anything, but I have not seen anyone else solving issues like this the way I did, so I am not sure, if I am missing something...
    – T-Dog
    Aug 14, 2020 at 14:29
  • I dont have much experience with threading and I'm not sure if there is a common way to do this. What I did in my only code with threading was target=callback and at the end of that callback I had set a IntVar() and I was working with wait_variable() in my other 2 functions. So I didnt needed the after method. Dont know if it helps, but since they closed your Question on Code Review I do not know if there will be another help here. Aug 14, 2020 at 14:45
  • Maybe try at StackExchange codereview.meta.stackexchange.com/a/1957/228833 Aug 14, 2020 at 14:55
  • 2
    Thank you, this sounds interesting! Do you have a reference to the mentioned code? If I understood right, this is similar to the logic I apply here, but I am not sure if wait_variable() could substitute my after() call here. But I think that my call of after() should be fine...at least I hope that I do not miss anything. Regarding the closed question: I reorganized the question & think that this is a good contribution to the community. Especially the examples with matplotlib embedding in tkinter as well as blitting are hard to research & not to be found comprehensive like in this code.
    – T-Dog
    Aug 14, 2020 at 15:01

1 Answer 1

2

So I did it like this but I do not know if it fits to you or if this is a good way to do this, but it safes you the .after as stated in the comments, which has the benefit that your function do_stuff is just called when needed.

import tkinter as tk
import time
import threading

def get_data():
    time.sleep(3)
    print('sleeped 3')
    _check.set(1)

def do_stuff():
    try:
        root.configure(bg='#'+str(_var.get()))
        _var.set(_var.get()+101010)
    except:
        _var.set(101010)

root = tk.Tk()
_check = tk.IntVar(value=0)
_var = tk.IntVar(value=101010)


def callback(event=None, *args):
    t1 = threading.Thread(target=get_data)
    t1.start()
    
    do_stuff()
    
_check.trace_add('write', callback) #kepp track of that variable and trigger callback if changed
callback() # start the loop



root.mainloop()

Some research:

[The Tcl]

interpreter is only valid in the thread that created it, and all Tk activity must happen in this thread, also. That means that the mainloop must be invoked in the thread that created the interpreter. Invoking commands from other threads is possible; _tkinter will queue an event for the interpreter thread, which will then execute the command and pass back the result.

#l1493 var_invoke

 The current thread is not the interpreter thread.  Marshal

       the call to the interpreter thread, then wait for

       completion. */

    if (!WaitForMainloop(self))

        return NULL;

is-it-safe-to-use-a-intvar-doublevar-in-a-python-thread

When you set a variable, it calls the globalsetvar method on the master widget associated with the Variable. The _tk.globalsetvar method is implemented in C, and internally calls var_invoke, which internally calls WaitForMainLoop, which will attempt schedule the command for execution in the main thread, as described in the quote from the _tkinter source I included above.

wiki.tcl

     Start
       |
       |<----------------------------------------------------------+
       v                                                           ^
   Do I have    No[*]  Calculate how            Sleep for at       |
   work to do?  -----> long I may sleep  -----> most that much --->|
       |                                        time               |
       | Yes                                                       |
       |                                                           |
       v                                                           |
   Do one callback                                                 |
       |                                                           |
       +-----------------------------------------------------------+

Commonsense

from bugtracker:

Tkinter and threads.

If you want to use both tkinter and threads, the safest method is to make all tkinter calls in the main thread. If worker threads generate data needed for tkinter calls, use a queue.Queue to send the data to the main thread. For a clean shutdown, add a method to wait for threads to stop and have it called when the window close button [X] is pressed.

effbot

Just run all UI code in the main thread, and let the writers write to a Queue object; e.g.

Conclusion

The Way you did it and the way I did it dosent seem like the ideal but they seem not wrong at all. It depends on what is needed.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.