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:
- 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.
- 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)) 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()