Python Forum

Full Version: Plot on gui window
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,
I'm trying to embed a plot script on my gui however didn't succeed it yet. The task that the complete design performs is:

script 1: Reads data through serial link and save them on 9 separate files. NO PROBLEM
script 2: GUI CODE and Includes 2 TABs
TAB1: start/stop and reset buttons and print latest data read through serial link (stored on txt files)
TAB2: I am trying to show the plot in here!

Current version plots the data after pressing a button but after each press it generates another canvas instead updating the last one. My real wish is after starting the system it must update the plot continuously. I found a script on the web but my attempts to embed it to the gui was not successfull.

I' ve attached my current GUI and the mentioned script.

I'm not that much old about these issues so any suggestion is appreciated.

from tkinter import *
from threading import Timer
import time
import serial
from tkinter import ttk

import matplotlib
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg

from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
import numpy as np

import matplotlib.animation as anim

HMCC=Tk()
HMCC.title(" GUI v6.0 ")
HMCC.geometry("750x500")

global cont	# CONTINUE
global ch0,ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8

def start():
	
	port.write(str('A').encode())						# START byte
	print('STARTEDDD ... ')
	print(str('A').encode())	
	
	global ch0,ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8
	ch0=0
	ch1=0
	ch2=0
	ch3=0
	ch4=0
	ch5=0
	ch6=0
	ch7=0
	ch8=0
	global cont
	cont=True
	
	yenile()
	
def yenile():
	
	global ch0,ch1,ch2,ch3,ch4,ch5,ch6,ch7,ch8
	
	if ( cont ):
		c1.set(ch0)
		c2.set(ch1)
		c3.set(ch2)
		c4.set(ch3)
		c5.set(ch4)
		c6.set(ch5)
		c7.set(ch6)
		c8.set(ch7)
		c9.set(ch8)
		
		global timer						# Every time this function is called, # we will increment 1 centisecond (1/100 of a second)
		timer[2] += 1
        
		if (timer[2] >= 60):				# Every 60 second is equal to 1 min
			timer[2] = 0
			timer[1] += 1
			
		if (timer[1] >= 60):				# Every 60 min is equal to 1 hour
			timer[0] += 1
			timer[1] = 0
            
		timeString=pattern.format(timer[0], timer[1], timer[2])		# We create our time string here
		timeText.configure(text=timeString)							# Update the timeText Label box with the current time
		
		HMCC.after(1000, yenile) # every second...
		
def stop():
	
	port.write(str('B').encode())				# STOP byte
	print('STOPEDDD ... \n ')
	print(str('B').encode())

	global cont
	cont=False	
	
def reset():
	
	port.write(str('L').encode())				# Set RESET
	print("\n set RESET")
	print(str('L').encode())
	#time.sleep(1)
	port.write(str('M').encode())				# Reset RESET
	print("\n reset RESET\n")
	print(str('M').encode())

	global data_num
	data_num=0
	
	global timer
	timer = [0, 0, 0]
	timeText.configure(text='00:00:00')
	
def period_1sec():
	port.write(str('C').encode())
	print("\n Period Set as 1 Second")
	print(str('C').encode())

def period_5sec():
	port.write(str('D').encode())
	print("\n Period Set as 5 Seconds")
	print(str('D').encode())

def period_10sec():
	port.write(str('E').encode())
	print("\n Period Set as 10 Seconds")
	print(str('E').encode())

def period_30sec():
	port.write(str('F').encode())
	print("\n Period Set as 30 Seconds")
	print(str('F').encode())

def period_1min():
	port.write(str('G').encode())
	print("\n Period Set as 1 Minute")
	print(str('G').encode())

def period_5min():
	port.write(str('H').encode())
	print("\n Period Set as 5 Minutes")
	print(str('H').encode())

def period_10min():
	port.write(str('I').encode())
	print("\n Period Set as 10 Minutes")
	print(str('I').encode())

def period_30min():
	port.write(str('J').encode())
	print("\n Period Set as 30 Minutes")
	print(str('J').encode())

def period_1hour():
	port.write(str('K').encode())
	print("\n Period Set as 1 Hour")
	print(str('K').encode())

def _quit():
	HMCC.quit()     
	HMCC.destroy()

#///////////////////////////////////////////////////////////////////////
# PLOT TABI VE GRAFIK ISLEMLERI				  					     |
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

def plot_counts():
	
	f = Figure(figsize=(5, 4), dpi=100)

	canvas = FigureCanvasTkAgg(f, master=tab2)
	canvas.show()
	canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
	
	SMALL_SIZE = 5
	matplotlib.rc('font', size=SMALL_SIZE)
	matplotlib.rc('axes', titlesize=SMALL_SIZE)

	
	#---------CHANNEL 1 PLOT------------------------------------------------
	file_name_1='Channel_1_200718_1728.txt'
	y1 = np.loadtxt(file_name_1)
	len(y1)
	scaler = 1
	x_temp1 = list(range(1,len(y1)+1))
	x1 = [x_temp1/scaler for x_temp1 in x_temp1]

	a331 = f.add_subplot(3,3,1)
	a331.plot(x1, y1)

	#---------CHANNEL 2 PLOT------------------------------------------------
	file_name_2='Channel_2_200718_1728.txt'
	y2 = np.loadtxt(file_name_2)
	len(y2)
	scaler = 1
	x_temp2 = list(range(1,len(y2)+1))
	x2 = [x_temp2/scaler for x_temp2 in x_temp2]
	a332 = f.add_subplot(3,3,2)
	a332.plot(x2, y2)

	#---------CHANNEL 3 PLOT------------------------------------------------
	file_name_3='Channel_3_200718_1728.txt'
	y3 = np.loadtxt(file_name_3)
	len(y3)
	scaler = 1
	x_temp3 = list(range(1,len(y3)+1))
	x3 = [x_temp3/scaler for x_temp3 in x_temp3]
	a333 = f.add_subplot(3,3,3)
	a333.plot(x3, y3)

	#---------CHANNEL 4 PLOT------------------------------------------------
	file_name_4='Channel_4_200718_1728.txt'
	y4 = np.loadtxt(file_name_4)
	len(y4)
	scaler = 1
	x_temp4 = list(range(1,len(y4)+1))
	x4 = [x_temp4/scaler 
	for x_temp4 in x_temp4]
	a334 = f.add_subplot(3,3,4)
	a334.plot(x4, y4)

	#---------CHANNEL 5 PLOT------------------------------------------------
	file_name_5='Channel_5_200718_1728.txt'
	y5 = np.loadtxt(file_name_5)
	len(y5)
	scaler = 1
	x_temp5 = list(range(1,len(y5)+1))
	x5 = [x_temp5/scaler for x_temp5 in x_temp5]
	a335 = f.add_subplot(3,3,5)
	a335.plot(x5, y5)

	#---------CHANNEL 6 PLOT------------------------------------------------
	file_name_6='Channel_6_200718_1728.txt'
	y6 = np.loadtxt(file_name_6)
	len(y6)
	scaler = 1
	x_temp6 = list(range(1,len(y6)+1))
	x6 = [x_temp6/scaler for x_temp6 in x_temp6]
	a336 = f.add_subplot(3,3,6)
	a336.plot(x6, y6)

	#---------CHANNEL 7 PLOT------------------------------------------------
	file_name_7='Channel_7_200718_1728.txt'
	y7 = np.loadtxt(file_name_7)
	len(y7)
	scaler = 1
	x_temp7 = list(range(1,len(y7)+1))
	x7 = [x_temp7/scaler for x_temp7 in x_temp7]
	a337 = f.add_subplot(3,3,7)
	a337.plot(x7, y7)

	#---------CHANNEL 8 PLOT------------------------------------------------
	file_name_8='Channel_8_200718_1728.txt'
	y8 = np.loadtxt(file_name_8)
	len(y8)
	scaler = 1
	x_temp8 = list(range(1,len(y8)+1))
	x8 = [x_temp8/scaler for x_temp8 in x_temp8]
	a338 = f.add_subplot(3,3,8)
	a338.plot(x8, y8)

	#---------CHANNEL 9 PLOT------------------------------------------------
	file_name_9='Channel_9_200718_1728.txt'
	y9 = np.loadtxt(file_name_9)
	len(y9)
	scaler = 1
	x_temp9 = list(range(1,len(y9)+1))
	x9 = [x_temp9/scaler for x_temp9 in x_temp9]
	a339 = f.add_subplot(3,3,9)
	a339.plot(x9, y9)
	#-----------------------------------------------------------------------

#///////////////////////////////////////////////////////////////////////
# CONTROL & PLOT TABS				  		     					 | 
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
control_tab = ttk.Notebook(HMCC)
 
tab1 = ttk.Frame(control_tab)
control_tab.add(tab1, text='Control Tab')

tab2 = ttk.Frame(control_tab)
control_tab.add(tab2, text='Plot Tab')

control_tab.grid(row=1, column=0, columnspan=50, rowspan=50, sticky='NESW')
control_tab.pack(expand=1, fill='both')

#///////////////////////////////////////////////////////////////////////
# DROP DOWN MENU 				  									 | 
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

menubar = Menu(HMCC)

filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="1  sec ", command=period_1sec )
filemenu.add_command(label="5  sec ", command=period_5sec )
filemenu.add_command(label="10 sec ", command=period_10sec)
filemenu.add_command(label="30 sec ", command=period_30sec)
filemenu.add_command(label="1  min ", command=period_1min )
filemenu.add_command(label="5  min ", command=period_5min )
filemenu.add_command(label="10 min ", command=period_10min)
filemenu.add_command(label="30 min ", command=period_30min)
filemenu.add_command(label="1  hour", command=period_1hour)
#filemenu.add_separator()
#filemenu.add_command(label="EXIT", command = HMCC.destroy)
menubar.add_cascade(label ="Period ", menu=filemenu)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index")
helpmenu.add_command(label="About...")
menubar.add_cascade(label ="Help", menu=helpmenu)

exitmenu = Menu(menubar, tearoff=0)
exitmenu.add_command(label="EXIT", command = HMCC.destroy)
menubar.add_cascade(label ="Quit", menu = exitmenu)

#///////////////////////////////////////////////////////////////////////
# BUTTONS				  				   			 				 | 
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

button1 = Button(tab1,text="START", fg="black", command=start )
button1.place(relx=.1, rely=.30, anchor="c")
button1.config(font="none 20 bold")

button2 = Button(tab1,text="STOP" , fg="black", command=stop)
button2.place(relx=.1, rely=.55, anchor="c")
button2.config(font="none 20 bold")

button3 = Button(tab1,text="RESET", fg="black", command=reset)
button3.place(relx=.1, rely=.92, anchor="c")
button3.config(font="none 10 bold")

#button4 = Button(text="QUIT" , fg="black", command=HMCC.destroy)
#button4.config(font="none 10 bold")#, background="Yellow")
#button4.place(relx=.9, rely=.92, anchor="c")

button5 = Button(tab1,text="PLOT" , fg="black", command=plot_counts)
button5.place(relx=.1, rely=.20, anchor="c")
button5.config(font="none 10 bold")

#///////////////////////////////////////////////////////////////////////
# INFO NEXT TO COUNTS 			 									 |
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Channel_1 = Label(tab1, text = "Channel 1 : ")		
Channel_2 = Label(tab1, text = "Channel 2 : ")		
Channel_3 = Label(tab1, text = "Channel 3 : ")		
Channel_4 = Label(tab1, text = "Channel 4 : ")		
Channel_5 = Label(tab1, text = "Channel 5 : ")		
Channel_6 = Label(tab1, text = "Channel 6 : ")		
Channel_7 = Label(tab1, text = "Channel 7 : ")		
Channel_8 = Label(tab1, text = "Channel 8 : ")		
Channel_9 = Label(tab1, text = "Channel 9 : ")		

Channel_1.place(relx=.31, 	rely=.70, 	anchor="c")
Channel_2.place(relx=.31, 	rely=.45, 	anchor="c")
Channel_3.place(relx=.31, 	rely=.20,	anchor="c")
Channel_4.place(relx=.55,	rely=.45, 	anchor="c")
Channel_5.place(relx=.55,	rely=.20, 	anchor="c")
Channel_6.place(relx=.80, 	rely=.20, 	anchor="c")
Channel_7.place(relx=.80, 	rely=.45, 	anchor="c")
Channel_8.place(relx=.80, 	rely=.70, 	anchor="c")
Channel_9.place(relx=.55,	rely=.70, 	anchor="c")

Channel_1.config(font="none 15 bold")
Channel_2.config(font="none 15 bold")
Channel_3.config(font="none 15 bold")
Channel_4.config(font="none 15 bold")
Channel_5.config(font="none 15 bold")
Channel_6.config(font="none 15 bold")
Channel_7.config(font="none 15 bold")
Channel_8.config(font="none 15 bold")
Channel_9.config(font="none 15 bold")

#///////////////////////////////////////////////////////////////////////
# LOCATIONS WHERE THE COUNTS WILL BE WRITTEN			  		 	 |
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

c1 = IntVar()
c2 = IntVar()
c3 = IntVar()
c4 = IntVar()
c5 = IntVar()
c6 = IntVar()
c7 = IntVar()
c8 = IntVar()
c9 = IntVar()

count_1 = Label(tab1, textvariable=c1)	
count_2 = Label(tab1, textvariable=c2)	
count_3 = Label(tab1, textvariable=c3)
count_4 = Label(tab1, textvariable=c4)
count_5 = Label(tab1, textvariable=c5)
count_6 = Label(tab1, textvariable=c6)
count_7 = Label(tab1, textvariable=c7)
count_8 = Label(tab1, textvariable=c8)
count_9 = Label(tab1, textvariable=c9)

count_1.place(relx=.30, rely=.80, anchor="c")
count_2.place(relx=.30, rely=.55, anchor="c")
count_3.place(relx=.30, rely=.30, anchor="c")
count_4.place(relx=.55, rely=.55, anchor="c")
count_5.place(relx=.55, rely=.30, anchor="c")
count_6.place(relx=.80, rely=.30, anchor="c")
count_7.place(relx=.80, rely=.55, anchor="c")
count_9.place(relx=.55, rely=.80, anchor="c")
count_8.place(relx=.80, rely=.80, anchor="c")

count_1.config(font="none 25 ")
count_2.config(font="none 25 ")
count_3.config(font="none 25 ")
count_4.config(font="none 25 ")
count_5.config(font="none 25 ")
count_6.config(font="none 25 ")
count_7.config(font="none 25 ")
count_8.config(font="none 25 ")
count_9.config(font="none 25 ")

#///////////////////////////////////////////////////////////////////////
# ELAPSED TIME FOR THE MEASUREMENTS				  		 		 	 |
#\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Elapsed_Time_Info = Label(tab1, text = "Elapsed Time: ")
Elapsed_Time_Info.place(relx=.45, rely=.92, anchor="c")
Elapsed_Time_Info.config(font="none 12 bold")

timer		= [0, 0, 0]											# Our time structure [min, sec, centsec]
pattern 	= '{0:02d}:{1:02d}:{2:02d}'							# The format is padding all the 
timeText	= Label(tab1, text="00:00:00", font=("none 15"))	# Create a timeText Label (a text box)
timeText.place(relx=.60, rely=.92, anchor="c")

HMCC.config(menu=menubar)
HMCC.mainloop()
This code does what I want to do and I'm searching for how to embed it to tab2 on above GUI

from tkinter import *
from random import randint
 
# these two imports are important
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import time
import threading

continuePlotting = False

def change_state():
    global continuePlotting
    if continuePlotting == True:
        continuePlotting = False
    else:
        continuePlotting = True
		
		
def data_points():
    f = open("data.txt", "w")
    for i in range(10):
        f.write(str(randint(0, 10))+'\n')
    f.close()
	
    f = open("data.txt", "r")
    data = f.readlines()
    f.close()
	
    l = []
    for i in range(len(data)):
        l.append(int(data[i].rstrip("\n")))
    return l
	
def app():
    # initialise a window.
    root = Tk()
    root.config(background='white')
    root.geometry("1000x700")
    
    lab = Label(root, text="Live Plotting", bg = 'white').pack()
	
    fig = Figure()
    
    ax = fig.add_subplot(1,1,1)
    ax.set_xlabel("X axis")
    ax.set_ylabel("Y axis")
    ax.grid()
	
    canvas = FigureCanvasTkAgg(fig, master=root)
    canvas.get_tk_widget().pack(side="top", fill='both', expand=True)
	
    def plotter():
        while continuePlotting:
            ax.cla()
            ax.grid()
            dpts = data_points()
            len(dpts)
            scaler = 1
            x_temp1 = list(range(1,len(dpts)+1))
            x1 = [x_temp1/scaler for x_temp1 in x_temp1]
            
            ax.plot(x1, dpts, marker='o', color='orange')
            canvas.draw()
            time.sleep(1)
			
    def start_stop():
        change_state()
        threading.Thread(target=plotter).start()
		
    b = Button(root, text="Start/Stop", command=start_stop)
    b.pack()
    
    root.mainloop()
	
if __name__ == '__main__':
    app()
Thanks in advance !
Sorry but the second code must be this one

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time

fig = plt.figure()

def animate(i):
	
	ax1 = fig.add_subplot(1,1,1)
	pullData1 = open("data1.txt","r").read()
	dataArray1 = pullData1.split('\n')
	xar = []
	yar = []
	
	for eachLine in dataArray1:
		if len(eachLine)>1:
			x1,y1 = eachLine.split(',')
			xar.append(int(x1))
			yar.append(int(y1))
	ax1.clear()
	ax1.plot(xar,yar)
	
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()