Search code examples
pythontkinterarduinopython-multiprocessingpyserial

Read analog value from Arduino and display it on a Tkinter GUI in real time


I'm trying to create a Python Tkinter GUI for a simple data transmission between an Arduino and a PC via Serial communication (I'm using pySerial package). I can input and send data from the GUI to the Arduino correctly. In a separated code file, I can also read data sent from Arduino correctly, but I have a problem with integrating this real-time data reading feature into the Tkinter GUI program and display it on the GUI. From my experiment, to properly read data sent from the Arduino, the reading need to be run in a loop. Tkinter also has its own loop. So to avoid being stuck in the data reading loop, I've been trying to run them in parallel using concurrent.futures, but it still doesn't work as I want. Please help!

Here's my code: https://drive.google.com/file/d/1xHOV-qXjg2iEA-PXa52d1_66bOpdbnzv/view?usp=sharing (Please understand that I'm still learning Python, Tkinter and multiprocessing. So there could be some mistakes on conventions and terminology.)

And this is what the GUI looks like: Arduino-PC Serial Communication GUI


Solution

  • Tkinter windows have a after method that can be used to run your own code as part of the Tkinter loop, for example:

    from tkinter import Tk
    
    window = Tk()
    
    def do_something():
        print("doing something!")
        window.after(1000, do_something)  # every 1000 milliseconds
    
    # start the do_something function immediately when the window starts
    window.after(0, do_something)
    
    window.mainloop()