[Tutor] Tkinter and matplotlib

Phil phillor9 at gmail.com
Fri Feb 11 01:35:24 EST 2022


I've used matplotlib in a stand-alone fashion but now I want to use 
matplotlib on a tkinter canvas so that I can add buttons to control 
what's happening.

There are many examples to be found on the Internet; some are dated and 
use Python2 while some are overly complex. Referring to one that I found 
one that I have greatly simplified (code following) I don't understand 
exactly what the purpose of "lines = ax.plot([],[])[0]" is and where  " 
lines.set_xdata(Time) and "lines.set_ydata(data)" comes from. I only 
know that they're needed to plot something. I have checked the 
matplotlib document page and other references.

As I say, many examples seem to be dated. Is this the correct and 
current method to plot data on a tkinter canvas?

Also, I haven't seen "root.update();" used before adding buttons. 
Although I've little experience using tkinter I thought the something 
like this is the correct method:

class Root(tk.Tk):
     def __init__(self):
         super().__init__()

         self.button = ttk.Button(
             self.frame, text='Click this', command=self.button_click)

Would the following code be better worked into a class or not? I suppose 
the canvas goes onto a frame?

import time
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import tkinter as tk
import pyfirmata

data = []
Time = []
time0 = time.time()
cnt = 0

def plot_data():
     global data, Time, time0, cnt

     instance = time.time()
     Time.append(instance-time0)

     data.append(cnt)

     lines.set_xdata(Time) # Is lines.set_xdata() the correct method?
     lines.set_ydata(data)

     canvas.draw()
     cnt += 1

     root.after(1000,plot_data)

def plot_start():
     global cond
     cond = True

def plot_stop():
     global cond
     cond = False


#-----Main GUI code-----
root = tk.Tk()
root.title('Real Time Plot')
root.geometry("700x500")

#------create Plot object on GUI----------
# add figure canvas
fig = Figure();
ax = fig.add_subplot(111)    # I know what this means

ax.set_title('Serial Data');
ax.set_xlabel('Sample')
ax.set_ylabel('Voltage')
ax.set_xlim(0,100)
ax.set_ylim(0, 100)
lines = ax.plot([],[])[0]    # I don't know this means

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().place(x = 10,y=10, width = 500,height = 400)
canvas.draw()

#----------create button---------
root.update();
start = tk.Button(root, text = "Start", font = ('calbiri',12),command = 
lambda: plot_start())
start.place(x = 100, y = 450 )

root.update();
stop = tk.Button(root, text = "Stop", font = ('calbiri',12), command = 
lambda:plot_stop())
stop.place(x = start.winfo_x()+start.winfo_reqwidth() + 20, y = 450)


root.after(1000,plot_data)
root.mainloop()

-- 

Regards,
Phil



More information about the Tutor mailing list