2
\$\begingroup\$

I have written a piece of code where I have a simple GUI with an Tkinter Canvas. On this canvas I draw an Matplot. The Matplot is updated every second with fake sensor data i simulate in an SQLite DB (just for testing at the moment).

I reached most of my Goals for this test case. But a few Things i would like to have reviewed:

  1. The Performance seems to be not really good. The window is lagging if you drag it over the Desktop. I think this is caused by the redrawing of the Canvas. I tried to use threads but failed to not Interrupt my mainloop while updating the canvas.
  2. My Code seems pretty messy (I am a beginner and just learning how to Code in a good style). Every criticism and ideas to make it better are welcome.

So here is my Code so far:

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import sqlite3
from datetime import datetime
from random import randint

class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        root.update_idletasks()

        f = Figure(figsize=(15,5), dpi=55)        
        x=1
        ax = f.add_subplot(111)
        line, = ax.plot(x, np.sin(x))     

        def animate(i):
            # Open Database
            conn = sqlite3.connect('Sensor_Data.db')
            c = conn.cursor()
            # Create some fake Sensor Data    
            NowIs = datetime.now()
            Temperature = randint(0, 100)
            Humidity = randint(0, 100)
            # Add Data to the Database
            c = conn.cursor()
            # Insert a row of data
            c.execute("insert into Sensor_Stream_1 (Date, Temperature, Humidity) values (?, ?, ?)",
                        (NowIs, Temperature, Humidity))
            # Save (commit) the changes
            conn.commit()
            # Select Data from the Database
            c.execute("SELECT Temperature FROM Sensor_Stream_1 LIMIT 30 OFFSET (SELECT COUNT(*) FROM Sensor_Stream_1)-30") 
            # Gives a list of all temperature values 
            x = 1
            Temperatures = []

            for record in c.fetchall():    
                Temperatures.append(str(x)+','+str(record[0]))
                x+=1
            # Setting up the Plot with X and Y Values
            xList = []
            yList = []

            for eachLine in Temperatures:
                if len(eachLine) > 1:
                    x, y = eachLine.split(',')
                    xList.append(int(x))
                    yList.append(int(y))           

            ax.clear()

            ax.plot(xList, yList) 

            ax.set_ylim(0,100)
            ax.set_xlim(1,30)

            ax.tick_params(axis='both', which='major', labelsize=12)

            ax.grid(b=None, which='major', axis='both', **kwargs)


        label = tk.Label(root,text="Temperature / Humidity").pack(side="top", fill="both", expand=True)

        canvas = FigureCanvasTkAgg(f, master=root)
        canvas.get_tk_widget().pack(side="left", fill="both", expand=True)

        root.ani = animation.FuncAnimation(f, animate, interval=1000)

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

Here is my DB Schema:

CREATE TABLE `Sensor_Stream_1` (
    `Date`  TEXT,
    `Temperature`   INTEGER,
    `Humidity`  INTEGER
);
\$\endgroup\$
  • \$\begingroup\$ What Python version did you write this for and can you share your SQL schema? \$\endgroup\$ – Mast Jan 18 at 15:24
  • 1
    \$\begingroup\$ I write this for Python 3.6 (3.6.4 exactly). I never made an SQL Schema, how do i do this? \$\endgroup\$ – K-Doe Jan 18 at 15:36
  • 1
    \$\begingroup\$ It depends a bit on your SQLite manager, but there should be a database -> export database structure option (or similar) somewhere. \$\endgroup\$ – Mast Jan 18 at 16:01
  • 1
    \$\begingroup\$ I added it to the bottom of my post. \$\endgroup\$ – K-Doe Jan 18 at 16:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.