How to plot an automatic graph using mouse without clicking MATPLOTLIB - python

I'm looking to plot Data automatically using mouse without clicking From a DZT file.
i Created a program in order to plot data as you can see in this graph:
As you can see in this picture, x axes going from 0 to 3525 ans every x is a signal so i have more than 3500 signals making this graph.
for exemple if i want to see the signal of x=999, it looks like this.
what i want really to do is every time when i pass my mouse without clicking on the graph it should plot it's signal automatically .
i try to use a lot of methods but rally i dont know how to do it.
i'll be grateful for your help
this is my file:
https://www.grosfichiers.com/mvabGETFfna
This is my program:
from tkinter import *
from tkinter import messagebox, filedialog
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import os
from readgssi import readgssi
root = Tk()
root.title("IHM")
root.geometry("1000x800")
Resources_frame = LabelFrame(root, bd=2, relief=GROOVE, text="Conversion Area")
Resources_frame.place(x=5, y=5, width=250, height=80)
lbl_ra = Label(Resources_frame, text="Select your File ")
lbl_ra.grid(row=0, column=0, sticky=W)
lbl_ra = Label(Resources_frame, text="Convert Selected file ")
lbl_ra.grid(row=1, column=0, sticky=W)
NumberOfSimples = ''
DataAScan = ''
Data = ''
xData = ''
xAxes = ''
def ReadDZT():
file_path = filedialog.askopenfilename()
file_name, file_extension = os.path.splitext(file_path)
print(file_extension)
if file_extension == '.DZT':
messagebox.showinfo("INFO", "Your DZT File Has Been Selected Successfully")
hdr, arrs, gps = readgssi.readgssi(infile=file_path, verbose=True)
TimeRange = hdr['rhf_range']
Samples = hdr['rh_nsamp']
X_Axes = np.array(range(0, Samples))
xAxes = X_Axes[2::1]
df = pd.DataFrame(arrs[0])
Data = df.iloc[2::1, 0::1]
fig2 = plt.figure()
plt.plot(xAxes, Data[999])
plt.show()
fig = plt.figure()
plt.imshow(Data, aspect='auto', cmap='bone')
plt.show()
elif file_extension == '.csv':
messagebox.showinfo("INFO", "Your CSV File Has Been Selected Successfully")
df = pd.read_csv(file_path)
NumberOfSimples = df.iloc[2::1, 0]
Data = df.iloc[::1, ::1]
DataAScan = df.iloc[2::1, 999]
fig1 = plt.figure()
plt.plot(NumberOfSimples, DataAScan)
plt.show()
fig2 = plt.figure()
plt.imshow(Data, aspect='auto', cmap='bone')
plt.show()
else:
messagebox.showwarning("WARNING", "You Have Been Selected a Different Format")
# =============Resources Buttons================#
btn_rs = Button(Resources_frame, relief=GROOVE, padx=8, pady=1, text="Browse", command=ReadDZT).grid(row=0,
column=1)
root.mainloop()

As indicated in the previous question Ploting a graph automatically using mouse coordinate (and I think this question should have been an edit of it), the mouse motion can be monitored with plt.connect('motion_notify_event', mouse_move). The slice of Data to be plotted in fig2 simply corresponds to the x-coordinate of the mouse, that is Data[int(event.xdata)] in mouse_move(event).
Therefore, in mouse_move(event), you:
Clear the axis: ax2.clear() (where ax2 is the AxesSubplot object of fig2)
Plot the slice ax2.plot(self.xAxes, self.Data[int(event.xdata)])
Update the figure fig2.canvas.draw_idle()
However, I had issues with using simultaneously the matplotlib figures and the tkinter GUI because of the separate event loops. Therefore I embedded the figures in the tkinter GUI directly (see e.g. https://matplotlib.org/3.4.0/gallery/user_interfaces/embedding_in_tk_sgskip.html).
I also put the graph related code in a class to keep the loaded data in attributes to avoid using global variables.
import tkinter as tk
from tkinter import messagebox, filedialog
import pandas as pd
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import numpy as np
import os
from readgssi import readgssi
class Graphs(tk.Toplevel):
def __init__(self, master=None, **kw):
tk.Toplevel.__init__(self, master, **kw)
self.rowconfigure(0, weight=1)
self.rowconfigure(2, weight=1)
# data
self.Data = []
self.xData = []
self.xAxes = []
self.line = None
# figure1 : 2D data map
self.fig1 = Figure()
self.ax1 = self.fig1.add_subplot(111)
self.canvas1 = FigureCanvasTkAgg(self.fig1, self)
self.canvas1.draw()
self.canvas1.get_tk_widget().grid(sticky='ewsn')
self.toolbar1 = NavigationToolbar2Tk(self.canvas1, self, pack_toolbar=False)
self.toolbar1.grid(sticky="ew")
# figure 2: slice plot
self.fig2 = Figure()
self.ax2 = self.fig2.add_subplot(111)
self.canvas2 = FigureCanvasTkAgg(self.fig2, self)
self.canvas2.draw()
self.canvas2.get_tk_widget().grid(sticky='ewsn')
self.toolbar2 = NavigationToolbar2Tk(self.canvas2, self, pack_toolbar=False)
self.toolbar2.grid(sticky="ew")
# bind plotting to mouse motion
self.canvas1.mpl_connect('motion_notify_event', self.mouse_move)
def mouse_move(self, event):
x = event.xdata
if len(self.Data) and x is not None: # there is something to plot
self.ax2.clear()
x = int(x)
self.ax2.plot(self.xAxes, self.Data[x])
self.line.set_data([x, x], [len(self.Data), 0])
self.canvas1.draw_idle()
self.canvas2.draw_idle()
def readDZT(self):
file_path = filedialog.askopenfilename()
file_name, file_extension = os.path.splitext(file_path)
if file_extension == '.DZT':
messagebox.showinfo("INFO", "Your DZT File Has Been Selected Successfully")
hdr, arrs, gps = readgssi.readgssi(infile=file_path, verbose=True)
Samples = hdr['rh_nsamp']
X_Axes = np.array(range(0, Samples))
self.xAxes = X_Axes[2::1]
df = pd.DataFrame(arrs[0])
self.Data = df.iloc[2::1, 0::1]
# clear plots
self.ax1.clear()
self.ax2.clear()
# plot slice
self.ax2.plot(self.xAxes, self.Data[999])
self.canvas2.draw_idle()
# plot 2D map
self.ax1.imshow(self.Data, aspect='auto', cmap='bone')
self.line = self.ax1.plot([999, 999], [len(self.Data), 0], 'r')[0]
self.ax1.set_ylim(len(self.Data), 0)
self.canvas1.draw_idle()
else:
messagebox.showwarning("WARNING", "You Have Been Selected a Different Format")
root = tk.Tk()
root.title("IHM")
root.geometry("1000x800")
Resources_frame = tk.LabelFrame(root, bd=2, relief=tk.GROOVE, text="Conversion Area")
Resources_frame.place(x=5, y=5, width=250, height=80)
tk.Label(Resources_frame, text="Select your File ").grid(row=0, column=0, sticky=tk.W)
tk.Label(Resources_frame, text="Convert Selected file ").grid(row=1, column=0, sticky=tk.W)
graphs = Graphs(root)
btn_rs = tk.Button(Resources_frame, relief=tk.GROOVE, padx=8, pady=1, text="Browse",
command=graphs.readDZT).grid(row=0, column=1)
root.mainloop()

Related

Changing axis legends and update labels in a tkinter treeview

In this GUI I am plotting 3 graphs with legends. There are 2 toplevel windows which can be opened by buttons. From one toplevel I am changing plot legends. In the MWE, if you hit "save legs" the plot legends are updating all with 1. That treeview is editable, so the idea was that the user can edit the legends.
In the second toplevel I want to "get" the current plot legends and fill the 1st column with those legends. The idea is, if a user changed the legends by using the 1st toplevel, the second can be updated with the new legends by getting the current plot legends.
My problem is even if the plot legends are changed, the second toplevel is populated by the old plot legends. How can it be? I am getting the legends by ax.get_legend_handles_labels(). Also the legends are not correctly populating inside the column. I want Leg1, Leg2, Leg 3 separately in each row. Someone can suggest a way to fix this?
Here's the MWE,
import matplotlib.pyplot as plt
import numpy as np
from tkinter import ttk
import tkinter as tk
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)
import pandas as pd
plt.close("all")
root = tk.Tk()
root.geometry('800x600')
pi2 = [452,989,1488]
pout2 = [316,698,1057]
pout3 = [311,693,1048]
pout4 = [321,653,1068]
fig, ax = plt.subplots()
canvas = FigureCanvasTkAgg(fig,root)
ax.plot(pi2,pout2,'o-',label='Leg1')
ax.plot(pi2,pout3,'o-',label='Leg2')
ax.plot(pi2,pout4,'o-',label='Leg3')
ax.legend(loc = 'best', fontsize = 7)
canvas.draw()
canvas.get_tk_widget().pack()
def add_leg():
global leg
top_add = tk.Toplevel(root)
top_add.attributes('-topmost', 'true')
top_add.geometry("200x260")
def edit(event):
if tree_top.identify_region(event.x, event.y) == 'cell':
def ok(event):
tree_top.set(item, column, tree_entry.get())
tree_entry.destroy()
column = tree_top.identify_column(event.x) # identify column
item = tree_top.identify_row(event.y) # identify item
x, y, width, height = tree_top.bbox(item, column)
value = tree_top.set(item, column)
elif tree_top.identify_region(event.x, event.y) == 'nothing':
column = tree_top.identify_column(event.x) # identify column
x, y, width, height = tree_top.bbox(tree_top.get_children('')[-1], column)
if event.y > y:
def ok(event):
item = tree_top.insert("", "end", values=("", ""))
tree_top.set(item, column, tree_entry.get())
tree_entry.destroy()
y += height
value = ""
else:
return
else:
return
tree_entry = ttk.Entry(tree_top) # create edition entry
tree_entry.place(x=x, y=y, width=width, height=height, anchor='nw') # display entry on top of cell
tree_entry.insert(0, value) # put former value in entry
tree_entry.bind('<FocusOut>', lambda e: tree_entry.destroy())
tree_entry.bind('<Return>', ok) # validate with Enter
tree_entry.focus_set()
tree_top = ttk.Treeview(top_add, show='headings', columns=("1", "2"))
tree_top['show'] = 'headings'
tree_top.column("#0", width=0)
tree_top.column("1", anchor=tk.CENTER, width=80)
tree_top.heading("1", text="File Name")
tree_top.column("2", anchor=tk.CENTER, width=80)
tree_top.heading("2", text="New Legend")
for i in range(3):
item = tree_top.insert("", "end",values=("",1))
tree_top.item(item, tags=item)
tree_top.bind('<1>', edit)
tree_top.place(x=7,y=7)
def save_leg():
global df_leg, new_legs,leglst
leglst = []
for i in tree_top.get_children():
row=tree_top.item(i)['values']
leglst.append(row)
leglst = list(map(list,leglst))
df_leg = pd.DataFrame(leglst,columns = ['File Name', 'New Legend'])
new_legs = df_leg['New Legend']
ax.legend(new_legs,loc = 'upper left', bbox_to_anchor=(0.01,0.7), framealpha=0.5, fontsize = 8)
canvas.draw()
saveleg_btn = tk.Button(top_add,text="Save Legs",command=lambda:save_leg())
saveleg_btn.place(x=0,y=100)
def top():
global data,lt,new_legs
topi = tk.Toplevel(root)
topi.geometry("200x250")
tree = ttk.Treeview(topi)
tree['columns']=('File Name','Pump %')
tree.column('#0', width=0, stretch=tk.NO)
tree.column('File Name', anchor=tk.CENTER, width=100)
tree.heading('#0', text='', anchor=tk.CENTER)
tree.heading('File Name', text='File Name', anchor=tk.CENTER)
tree.place(x=0,y=0)
lt = ax.get_legend_handles_labels()
tree.insert('', tk.END, values=(lt[-1],""))
addleg_btn = tk.Button(root,text="Add Legends",command=lambda:add_leg())
addleg_btn.pack()
top_btn = tk.Button(root,text="Ratios",background="#707087",command=lambda:top())
top_btn.pack()
root.mainloop()

finding peaks in a vibration signal

I am new in python and I just graduated and my thesis was about vibratory analysis, so when I started learning python. I wanted to make an an app that reads the signal and gives spesific informations about the graph such as peaks, here is what I have for now
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog as fd
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
import numpy as np
import os
Raw_1 = []
Raw_2 = []
clean_1 = []
clean_2 = []
# create the root window
root = tk.Tk()
root.title("Yazid ")
root.resizable(True, True)
root.geometry("400x400")
# full screen
class FullScreenApp(object):
def __init__(self, master, **kwargs):
self.master = master
pad = 3
self._geom = "200x200+0+0"
master.geometry(
"{0}x{1}+0+0".format(
master.winfo_screenwidth() - pad, master.winfo_screenheight() - pad
)
)
master.bind("<Escape>", self.toggle_geom)
def toggle_geom(self, event):
geom = self.master.winfo_geometry()
print(geom, self._geom)
self.master.geometry(self._geom)
self._geom = geom
def select_file():
filetypes = (("text files", "*.txt"), ("All files", "*.*"))
# get the txt file
filename = fd.askopenfilename(
title="select file", initialdir="/", filetypes=filetypes
)
# Get the raw list
for line in open(filename, "r"):
lines = [i for i in line.split(" ")]
Raw_1.append(lines[0].replace(",", "."))
Raw_2.append(lines[1].replace(",", "."))
# clean means get rid of the first three lines
for item in Raw_1[3:]:
clean_1.append(item)
for item in Raw_2[3:]:
clean_2.append(item)
# convert to float (geting the X and Y axes)
x = [float(i) for i in clean_1]
y = [float(i) for i in clean_2]
# plotting the points
fig = plt.figure()
ax = fig.subplots()
ax.plot(x, y, color="r")
ax.grid()
# naming the x axis
plt.xlabel(Raw_2[0])
# naming the y axis
plt.ylabel(Raw_1[0])
# title graph
fname = os.path.splitext(filename)[0]
name = os.path.basename(fname)
plt.title(name)
# Defining the cursor
cursor = Cursor(ax, horizOn=True, vertOn=True, useblit=True, color="r", linewidth=1)
# Creating an annotating box
annot = ax.annotate(
"",
xy=(0, 0),
xytext=(-40, 40),
textcoords="offset points",
bbox=dict(boxstyle="round4", fc="linen", ec="k", lw=1),
arrowprops=dict(arrowstyle="-|>"),
)
annot.set_visible(False)
# function to show the plot
plt.show()
# open button
open_button = ttk.Button(root, text="Open a File", command=select_file)
open_button.pack(expand=True)
# run the application
root.mainloop()
I am removing the first three lines because the first line contains the name of each column and the next two lines have some transient (I have more than 1600 values)
My code gives the following result
I want it to mark those peaks and give me their value on the y axes
and thank you
You could start with scipy.signal.find_peaks. In the documentation you will find how to do an example like this.
The orange crosses are the points selected with find_peaks, you have several parameters to tune, and it will probably be more productive than if you try to implement from scratch. After that if your can do a better job what is done by that function you can contribute to the library with your implementation.

How do I plot multiple files in a single graph?

I am new to programming. This program I have here is to read and plot 'n' files of xvg format to compare the graphs.
I want the program to be able to let me add as many xvg files as I want and plot them all in a single graph(each of different color) so that they can be compared.
I wrote the program and was able to plot the graph for only a single file at a time. Each file is opening up in a new window.
from tkinter import *
import matplotlib.pyplot as plt
import numpy as np
from tkinter import filedialog
plt.rcParams.update({'font.size':15})
root = Tk()
root.title("Graph plotter")
root.geometry("900x800")
def processxvg(filename):
x, y = [], []
with open(filename) as f:
for line in f:
if line[0] != "#" and line[0] != "#":
cols = line.split()
if len(cols) == 2:
x.append(float(cols[0]))
y.append(float(cols[1]))
return x,y
def random_color():
levels = range(32,256,32)
return tuple(random.choice(levels) for _ in range(3))
def browsefunc():
global filename
filename = filedialog.askopenfilename()
pathlabel.config(text=filename)
def addbox():
browsebutton = Button(root, text="Browse", command=browsefunc)
browsebutton.pack()
my_label = Label(root, text= "Browse the xvg file in the dir", font =("Ariel", "20") )
my_label.pack()
pathlabel = Label(root)
pathlabel.pack()
def clicked1():
(x, y) = processxvg(filename)
f = plt.figure()
f.set_figwidth(20)
f.set_figheight(10)
plt.plot(x,y)
plt.xlabel("Time (ns)", fontsize="35", labelpad=25)
plt.ylabel("RMSD (nm)", fontsize="35", labelpad=25)
plt.legend()
plt.show()
add_files_button = Button(root, text ="Add files", command = addbox)
add_files_button.pack()
plotbutton = Button(root, text ="Plot", command = clicked1 )
plotbutton.pack(pady = 10)
root.mainloop()
You are currently creating a new figure object every time the clicked1 function is called. The simplest solution would be to bring the figure creation outside of the function definition. I would also explicitly use the axis object to ensure everything plots on the same axis:
f, ax = plt.subplots(figsize=(20, 10))
ax.set_xlabel("Time (ns)", fontsize="35", labelpad=25)
ax.set_ylabel("RMSD (nm)", fontsize="35", labelpad=25)
plt.ion() # Enable interactive plotting
def clicked1():
(x, y) = processxvg(filename)
ax.plot(x,y)
ax.legend()
plt.show()
Ideally you would not use global variables, but instead pass ax as an argument to clicked1.

Button Not Working in Tkinter Python Application

I am writing a python application using tkinter that plots weather data on a map. I am currently testing out my button that is supposed to plot the data on the map I created using basemap. However, when I run my program, my button does nothing. I defined my function that plots the data and called the function in the command attribute of my button. Anyone know what the problem could be?
import tkinter as tk
from tkinter import ttk
import tkinter.font as tkFont
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
import requests
lon = [-76.5152, -76.7311, -76.3055, -76.7277, -75.4714, -75.1652, -77.0011, -75.6624, -78.3947, -77.8600, -78.7583, -79.9959, -80.0851]
lat = [40.3295, 40.1998, 40.0379, 39.9626, 40.6023, 39.9526, 41.2412, 41.4090, 40.5187, 40.7934, 41.1210, 40.4406, 42.1292]
def current_weather():
key = '4a7a419e4e16e2629a4cedc37cbf7e50'
url = 'https://api.openweathermap.org/data/2.5/weather'
global observation
observation = []
for i in range(0,len(lon)):
params = {'lat': lat[i], 'lon': lon[i], 'appid': key, 'units': 'imperial'}
response = requests.get(url, params = params)
weather = response.json()
observation.append(round(weather['main']['temp']))
current_weather()
root = tk.Tk()
#place map on canvas
fig = Figure(figsize=(5, 4), dpi=100)
ax = fig.add_subplot(111)
map = Basemap(llcrnrlon=-80.5, llcrnrlat=39.8, urcrnrlon=-74.7, urcrnrlat=42.3,resolution='i',
lat_0 = 40., lon_0 = -80, ax = ax)
map.drawmapboundary(fill_color='#A6CAE0')
map.drawcounties(zorder = 20)
map.drawstates()
map.fillcontinents(color='#e6b800',lake_color='#A6CAE0')
def plot_data():
for i in range(0, len(lon)):
x,y = map(lon[i], lat[i])
ax.text(x, y, observation[i], fontsize = 7)
#create widgets
canvas = FigureCanvasTkAgg(fig, master = root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
radiovalue = tk.IntVar()
temperature = tk.Radiobutton(root, text = "Plot current temperatures", variable = radiovalue, value = 1)
dewpoint = tk.Radiobutton(root, text = "Plot current dewpoints", variable = radiovalue, value = 2)
wind = tk.Radiobutton(root, text = "Plot current winds", variable = radiovalue, value = 3)
button = tk.Button(root, text = "Plot", command = plot_data)
#organize widgets
temperature.place(relx = 0.025, rely = 0.8)
dewpoint.place(relx = 0.385, rely = 0.8)
wind.place(relx = 0.675, rely = 0.8)
button.place(relx = 0.35, rely = 0.1)
root.mainloop()

Can interact only with the last graph

I'm practicing tkinter and matplotlib.
I wrote this piece of code which creates an entered number of frames and in each frame a different plot is embedded. I can then go from plot to plot by switching between the created frames and turn a drawing mode on. What the drawing mode do is enable me to click on the plot and create a horizontal line on it.
But when I turn drawing mode on I can only interact with the last graph.
Any ideas why this is happening?
The piece of code:
from tkinter import *
from random import *
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
numberOfFrames = eval(input('Number of frames to be crated: '))
x = []
y = []
class app(Tk):
def __init__(self):
Tk.__init__(self)
self.geometry('640x400')
self.frames = []
self.currentPage = 0
def nextpage():
try:
frame = self.frames[self.currentPage+1]
frame.tkraise()
self.currentPage += 1
except:
pass
def backpage():
if self.currentPage == 0:
pass
else:
frame = self.frames[self.currentPage-1]
frame.tkraise()
self.currentPage -= 1
def DrawOn():
def onclick(event):
plt.hlines(event.ydata,event.xdata-0.1,event.xdata+0.1,
colors='r',linestyle='solid')
canvas.show()
fig.canvas.mpl_connect('button_press_event', onclick)
for i in range(numberOfFrames):
frame = Frame(self)
frame.grid(row=0, column=0, sticky="nsew")
self.frames.append(frame)
fig = plt.figure()
for j in range(2):
x.append(randint(1,10))
y.append(randint(1,10))
plt.plot(x,y)
canvas = FigureCanvasTkAgg(fig, self.frames[i])
canvas.get_tk_widget().pack(fill='both', expand=True)
toolbar = NavigationToolbar2TkAgg(canvas, self.frames[i])
toolbar.update()
canvas._tkcanvas.pack(fill='both', expand=True)
label = Label(self.frames[i], text='Page %d'%(i+1))
label.pack()
Next = Button(self.frames[i], text='Next', command = nextpage)
Next.pack(side=LEFT)
Back = Button(self.frames[i], text='Back', command = backpage)
Back.pack(side=LEFT)
Draw = Button(self.frames[i], text='Draw', command = DrawOn)
Draw.pack(side=LEFT)
self.frames[0].tkraise()
run = app()
run.mainloop()
That's the alteration I made to my code. It made possible to interact with all the embedded graphs. I'm not sure if it is the best way to do it, but it seems to work.
from tkinter import *
from random import *
import matplotlib
matplotlib.use('TkAgg')
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
numberOfFrames = eval(input('Number of frames to be crated: '))
x = []
y = []
class app(Tk):
def __init__(self):
Tk.__init__(self)
self.geometry('640x400')
self.frames = []
self.currentPage = 0
self.figs = []
self.axeslist = []
self.canvaslist = []
def nextpage():
try:
frame = self.frames[self.currentPage+1]
frame.tkraise()
self.currentPage += 1
except:
pass
def backpage():
if self.currentPage == 0:
pass
else:
frame = self.frames[self.currentPage-1]
frame.tkraise()
self.currentPage -= 1
def DrawOn():
def onclick(event):
self.axeslist[self.currentPage].hlines(event.ydata,event.xdata-0.1,event.xdata+0.1,
colors='r',linestyle='solid')
self.canvaslist[self.currentPage].show()
print(event.xdata,event.ydata)
for i in self.figs:
i.canvas.mpl_connect('button_press_event', onclick)
for i in range(numberOfFrames):
frame = Frame(self)
frame.grid(row=0, column=0, sticky="nsew")
self.frames.append(frame)
fig = plt.figure()
self.figs.append(fig)
ax = self.figs[i].add_subplot(111)
self.axeslist.append(ax)
for j in range(2):
x.append(randint(1,10))
y.append(randint(1,10))
plt.plot(x,y)
canvas1 = FigureCanvasTkAgg(self.figs[i], self.frames[i])
self.canvaslist.append(canvas1)
self.canvaslist[i].get_tk_widget().pack(fill='both', expand=True)
toolbar = NavigationToolbar2TkAgg(self.canvaslist[i], self.frames[i])
toolbar.update()
self.canvaslist[i]._tkcanvas.pack(fill='both', expand=True)
label = Label(self.frames[i], text='Page %d'%(i+1))
label.pack()
Next = Button(self.frames[i], text='Next', command = nextpage)
Next.pack(side=LEFT)
Back = Button(self.frames[i], text='Back', command = backpage)
Back.pack(side=LEFT)
Draw = Button(self.frames[i], text='Draw', command = DrawOn)
Draw.pack(side=LEFT)
self.frames[0].tkraise()
run = app()
run.mainloop()

Categories

Resources