Python Forum
[Tkinter] Newbie Trying to make Simple GUI
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Newbie Trying to make Simple GUI
#1
Question 
Hi everyone,
First time Python user and poster here - been playing with the program for a week or so now with minimal coding background. I am using Anaconda with Python 3.5 via Spyder.

I am trying to make a simple display to show data which I have coming from a sensor and being written to a .csv file. The data comes into the .csv looking like the following:
TimeStamp, ReadCount, Antenna, Protocol, RSSI, EPC, Sensor
09/20/2016 10:38:51.641, 693, 1, GEN2, -18, E036112D912508B3, 23.36,46.00,0.00,2.21, (Infinity%)
09/20/2016 10:38:52.157, 700, 1, GEN2, -18, E036112D912508B3, 23.36,46.00,0.00,2.18, (Infinity%)
09/20/2016 10:38:52.653, 707, 1, GEN2, -23, E036112D912508B3, 23.36,45.00,0.00,2.19, (Infinity%)
09/20/2016 10:38:53.139, 714, 1, GEN2, -25, E036112D912508B3, 23.36,45.00,0.00,2.18, (Infinity%)
09/20/2016 10:38:53.651, 721, 1, GEN2, -16, E036112D912508B3, 23.36,45.00,0.00,2.18, (Infinity%)
09/20/2016 10:38:54.165, 728, 1, GEN2, -18, E036112D912508B3, 23.36,44.00,0.00,2.18, (Infinity%)
From this data I am pulling the time and "Protocol" (tension) data and want to show a live graph of this data. I also want to show other information in the window which holds the graph in text box fields below the graph, which shows additional data from these fields.

I've successfully put code together which would pull the data and graph it as I liked, however am still struggling to get it to maintain a fixed amount of time on the x axis range, only showing data from the last x seconds. Additionally I can not figure out how to have the line plot not interpolate and create a connection between gaps of data (there are points when the sensor is not in a readable area and gaps occur, I would like to not have the line connect points between these gaps).

Because I want to show a window with the graph AND data fields below it, I figured a Tkinter GUI would be the way to go - I have not had any success following tutorials on how to get this to work. I have a code which I followed from various of Sentdex's tutorials (primarily Live Matplotlib Graphs and putting matplot lib graphs into tkinter )

I feel like I've followed his tutorial to the point where I should be having a window pop up with my live graph in it, however every time I try to run it Python crashes...

Any help with getting Tkinter to work and then on how I can add the x-axis limit/control and interpolation over gaps issues resolved?

Here is my code so far:
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datetime import datetime

import tkinter as tk

LARGE_FONT= ("Verdana", 24)

fig = Figure(figsize=(5,5), dpi = 100)
ax1 = fig.add_subplot(111)
#ax1 = fig.add_subplot(111, axisbg='#07000d') 
       
offset = -7.4954
slope = 0.9548

#fig = plt.figure(facecolor='#07000d')


ax1.spines['bottom'].set_color("#5998ff")
ax1.spines['top'].set_color("#5998ff")
ax1.spines['left'].set_color("#5998ff")
ax1.spines['right'].set_color("#5998ff")

    
def animate(i):
    graph_data = open('SensorLog.csv','r').read()
    dataArray = graph_data.split('\n')
    xar=[]
    yar=[]

    for eachLine in dataArray:
        if 'TimeStamp' not in eachLine: 
            if len(eachLine)>1:
                t,rc,ant,prot,rssi,epc,temp,ten,powr,unpowr,inf=(eachLine.split(','))         
                time = datetime.strptime(t, '%m/%d/%Y %H:%M:%S.%f')
                clock = time.strftime('%I:%M')
                xs = matplotlib.dates.datestr2num(clock)
                hfmt = matplotlib.dates.DateFormatter('%m/%d/%Y\n%I:%M:%S %p')

#                Convert tension
                tension = int(float(ten)*float(slope)+float(offset))
                xar.append(xs)
                yar.append(tension)
           
    ax1.clear()
    
    ax1.grid(True, color='w')

    plt.ylabel('Tension (lb)',color='w', fontsize=20)
    plt.title('Spiral 1 Tension',color='w', fontsize=26)

    ax1.tick_params(axis='y', colors='w')
    ax1.tick_params(axis='x', colors='w')
    ax1.xaxis.set_major_formatter(hfmt)
    fig.autofmt_xdate()
    
    ax1.plot (xar,yar)

class Monitor(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        container=tk.Frame(self)
        
        container.pack(side="top",fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        
        self.frames={}
        
        frame = StartPage(container, self)
        
        self.frames[StartPage]=frame
        
        frame.grid(row=0, column=0, stickey="nsew")
        self.show_frame(StartPage)
        
    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()
        
class StartPage(tk.Frame):
    def __init__(self,parent,controller):
        tk.Frame.__init__(self,parent)
                
        label = tk.Label(self, text="System Monitor", font= LARGE_FONT)
        label.pack(pady=10,padx=10)
        
        canvas = FigureCanvasTkAgg(fig, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True) 
       
        
app = Monitor()
ani = animation.FuncAnimation(fig, animate, interval=1000)
app.mainloop()
#plt.show()
Reply
#2
This line in "class Monitor", you misspelled "sticky"
If it ain't broke, I just haven't gotten to it yet.
OS: Windows 10, openSuse 42.3, freeBSD 11, Raspian "Stretch"
Python 3.6.5, IDE: PyCharm 2018 Community Edition
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020