How to update matplotlib embedded into tkinter? - python-3.x

The problem is that I want to draw a plot by clicking on a button but it doesn't work. However, when I call draw from __init__, the plot appears on the screen.
Plotter.py
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class Plotter(FigureCanvasTkAgg):
def __init__(self, master):
self.figure = Figure(dpi=100)
super().__init__(self.figure, master=master)
self.axes = self.figure.add_subplot(111)
self.get_tk_widget().grid(column=0, row=0, sticky='nsew')
def draw(self):
self.axes.clear()
x_list = [x for x in range(0, 100)]
y_list = [x^3 for x in x_list]
self.axes.plot(x_list, y_list, color='y')
MainApplication.py
from tkinter import ttk
import tkinter as tk
import plotter
class MainApplication(ttk.Frame):
def __init__(self, master, *args, **kwargs):
super().__init__(root)
self.grid(column=0, row=0, sticky='nsew')
frame = ttk.Frame(self, borderwidth=8)
frame.grid(column=0, row=0, sticky='nsew')
frame.rowconfigure(0, weight=1)
notes = ttk.Notebook(frame)
notes.grid(column=0, row=0, sticky='nsew')
notes.rowconfigure(0, weight=1)
page = ttk.Frame(notes)
notes.add(page, text='Picture')
plot = plotter.Plotter(page)
# plot.draw() # This call updates the plot
input_frame = ttk.Frame(self)
input_frame.grid(column=1, row=0, sticky='nsew')
# this binding doesn't update the plot
button = ttk.Button(input_frame, text='Plot', \
command=lambda: plot.draw())
button.grid(column=0, row=4, columnspan=2, sticky='ew')
root = tk.Tk()
MainApplication(root)
root.mainloop()

Personally I would write this up in a single class so that we can use class attributes and methods to control everything with ease. Also you do not need a lambda here. Just save the reference to the command button and not a lambda call. That said you were also overwriting the draw method of FigureCanvasTkAgg so change the draw() method to something else.
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
from tkinter import ttk
import tkinter as tk
class MainApplication(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
notes = ttk.Notebook(self)
notes.grid(column=0, row=0, sticky='nsew')
notes.rowconfigure(0, weight=1)
self.page = ttk.Frame(notes)
notes.add(self.page, text='Picture')
self.plotter()
input_frame = ttk.Frame(self)
input_frame.grid(column=1, row=0, sticky='nsew')
button = ttk.Button(input_frame, text='Plot', command=self.new_draw)
button.grid(column=0, row=4, columnspan=2, sticky='ew')
def plotter(self):
self.figure = Figure(dpi=100)
self.plot_canvas = FigureCanvasTkAgg(self.figure, self.page)
self.axes = self.figure.add_subplot(111)
self.plot_canvas.get_tk_widget().grid(column=0, row=0, sticky='nsew')
def new_draw(self):
self.axes.clear()
x_list = [x for x in range(0, 100)]
y_list = [x^3 for x in x_list]
self.axes.plot(x_list, y_list, color='y')
self.plot_canvas.draw_idle()
MainApplication().mainloop()

You overwrote the canvas' draw method without reimplementing it. But since you do not want to update your plot on every draw-event anyways, I'd suggest to call the method to update the plot differently, e.g. draw_lists. Inside draw_lists you would then need to call the draw method of the canvas (or in this case better draw_idle).
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
class Plotter(FigureCanvasTkAgg):
def __init__(self, master):
self.figure = Figure(dpi=100)
super().__init__(self.figure, master=master)
self.axes = self.figure.add_subplot(111)
self.get_tk_widget().grid(column=0, row=0, sticky='nsew')
def draw_lists(self):
self.axes.clear()
x_list = [x for x in range(0, 100)]
y_list = [x^3 for x in x_list]
self.axes.plot(x_list, y_list, color='y')
self.draw_idle()
from tkinter import ttk
import tkinter as tk
class MainApplication(ttk.Frame):
def __init__(self, master, *args, **kwargs):
super().__init__(root)
self.grid(column=0, row=0, sticky='nsew')
frame = ttk.Frame(self, borderwidth=8)
frame.grid(column=0, row=0, sticky='nsew')
frame.rowconfigure(0, weight=1)
notes = ttk.Notebook(frame)
notes.grid(column=0, row=0, sticky='nsew')
notes.rowconfigure(0, weight=1)
page = ttk.Frame(notes)
notes.add(page, text='Picture')
plot = Plotter(page)
input_frame = ttk.Frame(self)
input_frame.grid(column=1, row=0, sticky='nsew')
# this binding doesn't update the plot
button = ttk.Button(input_frame, text='Plot', \
command=lambda: plot.draw_lists())
button.grid(column=0, row=4, columnspan=2, sticky='ew')
root = tk.Tk()
MainApplication(root)
root.mainloop()

Related

How to Write Data to a File and Plot that File in TK LIVE

I have a sensor that is measuring temperature every second and i'm writing that data to a text file (.txt). I want to have a plot that updates AS the data is written to the file - a live plotter if you will. I have the majority of the framework written to plot the data and have a plot in the GUI that i'm still working on. That code is attached. As it is now, I can execute the code and open up the plotter. As I type data into the file manually and save it, the plot updates. But like I said, i'm looking to have it do that without me opening the file and manually saving it. The sensor would write to the file each second and the plot would just automatically update. In lieu of the sensor code, i've put in a rough skeleton set of code where the sensor code will go.
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import matplotlib.animation as animation
from matplotlib import style
from time import sleep
import tkinter as tk
from tkinter import ttk
LARGE_FONT= ("Verdana", 12)
style.use("ggplot")
f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)
# =============================================================================
# SENSOR DATA INPUT GOES HERE.
# x = random.random()
# y = random.random()
# f = "test_data.txt"
# f.open()
# f.write("test_data.txt,"a") #write to the file in x y format, no comma in between as the
deliniator is a space.
# =============================================================================
def animate(i):
pullData = open("test_data.txt","r").read()
dataList = pullData.split('\n')
xList = []
yList = []
for eachLine in dataList:
if len(eachLine) > 1:
x, y = eachLine.split(' ')
xList.append(float(x)) #int(x)
yList.append(float(y)) #int(y)
a.clear()
a.plot(xList, yList)
class Data_Acq(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# tk.Tk.iconbitmap(self, default="clienticon.ico")
tk.Tk.wm_title(self, "Data Acquisition")
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 = {}
for F in (StartPage,PageThree):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="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="Experiment Alpha", font=LARGE_FONT)
label.pack(pady=10,padx=10)
#button = ttk.Button(self, text="Visit Page 1",
# command=lambda: controller.show_frame(PageOne))
#button.pack()
#button2 = ttk.Button(self, text="Visit Page 2",
# command=lambda: controller.show_frame(PageTwo))
#button2.pack()
button3 = ttk.Button(self, text="Graph Page",
command=lambda: controller.show_frame(PageThree))
button3.pack()
class PageThree(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
label = tk.Label(self, text="Graph Page!", font=LARGE_FONT)
label.pack(pady=10,padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
canvas = FigureCanvasTkAgg(f, self)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
toolbar = NavigationToolbar2Tk(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
app = Data_Acq()
ani = animation.FuncAnimation(f, animate, interval=500)
app.mainloop()
So again, as I enter data into the text file in this format:
1 22.0
2 33.1
3 33.0
4 33.5
5 41.2
and hit save on each entry, it updates the graph.

How to create a class to close GUI and exit Python

I have been trying to find a way to do this for a while to no avail. I would like to create a class to completely close my GUI in tkinter and I'm not having much luck. I've tried sys.exit and .destroy() a few different ways. I can manage to do what I want without using classes but I'm rather new to OOP. Here is my code:
import sys as system
import tkinter as tk
from tkinter import ttk
class headerFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
#setup the grid layout manager
self.columnconfigure(0, weight=1)
self._create_widgets()
def _create_widgets(self):
#header bar
canvas = tk.Canvas(self, bg='#0066cc', highlightthickness=0, height=45, width=600)
canvas.grid(column=0, row=0, sticky=tk.W)
label = ttk.Label(self, text='Production Assistant', background='#0066cc', foreground='White', font=('calibri', 18, 'bold'))
label.grid(row=0, column=0)
class loginFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
#setup the grid layout manager
self.columnconfigure(0, weight =1)
self.columnconfigure(0, weight=3)
self._create_widgets()
def _create_widgets(self):
#username
ttk.Label(self, text='Username: ', justify='right').grid(row=0, column=0, sticky=tk.E)
username = ttk.Entry(self, width=33)
username.focus()
username.grid(row=0, column=1, sticky=tk.W)
#password
ttk.Label(self, text='Password: ', justify='right').grid(row=1, column=0, sticky=tk.E)
password = ttk.Entry(self, width=33, show='*')
password.grid(row=1, column=1, sticky=tk.W)
#add padding
for widget in self.winfo_children():
widget.grid(padx=0, pady=5)
class loginButtonFrame(ttk.Frame):
def __init__(self, container):
super().__init__(container)
#setup the grid layout manager
self.columnconfigure(0, minsize=62)
self._create_widgets()
def _create_widgets(self):
#buttons
ttk.Button(self, text='Login', width=15).grid(row=0, column=1)
ttk.Button(self, text='Forgot Login', width=15).grid(row=0, column=2)
ttk.Button(self, text='Request Access', width=15).grid(row=1, column=1)
ttk.Button(self, text='Exit', width=15, command=exitButton).grid(row=1, column=2)
#add padding to buttons
for widget in self.winfo_children():
widget.grid(padx=3, pady=3)
class exitButton():
def exit():
#code to close gui and program
#create the main application
class mainLogin(tk.Tk):
def __init__(self):
super().__init__()
self.title('Login')
self.geometry('325x175')
self.resizable(0, 0)
self.configure(background='#444444')
#windows only (remove the minimize/maximize buttons)
self.attributes('-toolwindow', True)
#TCL to center the screen
self.eval('tk::PlaceWindow . center')
#layout on the root window
self.columnconfigure(0, weight=1)
self._create_Styles()
self._create_widgets()
def _create_Styles(self):
#create styles
s = ttk.Style()
s.configure('TFrame', background='#444444')
s.configure('TLabel', background='#444444', foreground='white')
s.configure('TButton', background='#878683', foreground='black')
def _create_widgets(self):
#create the header frame
_header_frame = headerFrame(self)
_header_frame.grid(column=0, row=0)
#create the login frame
_login_frame = loginFrame(self)
_login_frame.grid(column=0, row=1, sticky=tk.N)
#create the button frame
_login_button_frame = loginButtonFrame(self)
_login_button_frame.grid(column=0, row=2)
if __name__ == '__main__':
app = mainLogin()
app.mainloop()
class exitButton() is what I would like to call from multiple different pages in the application to close everything.
Any help is appreciated, I'm trying to learn as I build so if you have any suggested reading based around Python that would help with this I would appreciate it!

Ttk Frame, Background color

I'm using ttk, for my GUI. I know that it is also a very simple question ... I am trying to change the background color of the main window.
I tried to change the theme, because I am working on a Mac, (and Python 3.5) to avoid the problem with the theme 'aqua', which is the default.I've been reading about several solutions like these questions which are about the same problem... These are the numbers of the questions:
54476511,
38712352,
47327266,
23750141.
But, I haven't Solve the problem, yet.
Here it's my code.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from tkinter.scrolledtext import *
from tkinter import Tk, BOTH, W, N, E, S, messagebox, END
from tkinter.ttk import Button, Label, Style, Frame
class Example(Frame):
def __init__(self,master):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Example")
Style().theme_use("classic")
self.pack(fill=BOTH, expand=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(3, pad=7)
self.rowconfigure(3, weight=1)
self.rowconfigure(5, pad=7)
self.txt_Pad = ScrolledText(self)
self.txt_Pad.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)
self.txt_Pad.insert(END,'Type your info here')
btn_save = Button(self, text="Save", command=self.save_command)
btn_save.grid(row=1, column=3)
btn_close = Button(self, text="Close", command=self.onClose)
btn_close.grid(row=2, column=3, pady=4)
btn_help = Button(self, text="Help", command=self.about_command)
btn_help.grid(row=5, column=0, padx=5)
def onClose(self):
self.master.destroy()
def about_command(self):
msb = messagebox.showinfo("About", "\"Insert a useful tip Here\"")
def save_command(self):
print('Your info it\'s save now')
def open_command(self):
print('Choose your File')
def main():
root = Tk()
root.geometry("350x300+300+300")
root.configure(bg='#0059b3')
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
Any Suggestions would be appreciated.
Create a style then apply it.
from tkinter.scrolledtext import *
from tkinter import Tk, BOTH, W, N, E, S, messagebox, END
from tkinter.ttk import Button, Label, Style, Frame
class Example(Frame):
def __init__(self, master):
super().__init__()
self.initUI()
def initUI(self):
self.master.title("Example")
# create a new style
self.style = Style()
# configure it to the background you want
self.style.configure('My.TFrame', background='#0059b3')
#Style().theme_use("classic")
# apply it
self.config(style='My.TFrame')
self.pack(fill=BOTH, expand=1)
self.columnconfigure(1, weight=1)
self.columnconfigure(3, pad=7)
self.rowconfigure(3, weight=1)
self.rowconfigure(5, pad=7)
self.txt_Pad = ScrolledText(self)
self.txt_Pad.grid(row=1, column=0, columnspan=2, rowspan=4, padx=5, sticky=E+W+S+N)
self.txt_Pad.insert(END,'Type your info here')
btn_save = Button(self, text="Save", command=self.save_command)
btn_save.grid(row=1, column=3)
btn_close = Button(self, text="Close", command=self.onClose)
btn_close.grid(row=2, column=3, pady=4)
btn_help = Button(self, text="Help", command=self.about_command)
btn_help.grid(row=5, column=0, padx=5)
def onClose(self):
self.master.destroy()
def about_command(self):
msb = messagebox.showinfo("About", "\"Insert a useful tip Here\"")
def save_command(self):
print('Your info it\'s save now')
def open_command(self):
print('Choose your File')
def main():
root = Tk()
root.geometry("350x300+300+300")
root.configure(background='#0059b3')
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
I left comments at the parts I changed.

Tkinter scrollbar for frame in a Frame

I'm creating a dynamic container that can change between frames. In one of the frames I have a list of values that I need to scroll through because it is so long. However I cannot get the scrollbar to work with the canvas and frame set up.
i have tried using Listbox and this works but does not give me the control over the displays that I am looking for. I want to be able to configure the names of the tag and then to the right the value.
#!Python
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import style
import tkinter as tk
from tkinter import *
from YahooParser import Yahoo_Parser
TITLE_FONT = ("Helvetica", 10, "bold")
LARG_FONT = ("Helvetica", 12)
NORM_FONT = ("Helvetica", 10)
AIR_FONT = ("Arial", 10)
SMALL_FONT = ("Helvetica", 8)
style.use("ggplot")
#style.use("ggplot")
Gray = "#%02x%02x%02x" % (85, 85, 85)
Wight ="#%02x%02x%02x" % (220, 220, 220)
class Midas_Screen(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# Title
tk.Tk.wm_title(self, "Midas Program")
tk.Tk.geometry(self,"500x400")
#tk.Tk.configure(self, background='black')
# This set the seting for the container
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 = {}
# Makes all the frames and stores them
for F in (HomePage,):
# You pass the container to your page function. this makes the frame
frame = F(container, self)
# this aligns the frame "nsew" = North, South etc
frame.grid(row=0, column=0, sticky="nsew")
# This uses the function as a key in the dic
self.frames[F] = frame
self.show_frame(HomePage)
def show_frame(self, key):
frame = self.frames[key]
frame.tkraise()
class HomePage(tk.Frame):
def __init__(self, perent, controller):
self.yp = Yahoo_Parser()
self.names = []
self.values = {}
for tag in self.yp.values_sum:
self.names.append(tag[0])
for tag in self.yp.values_sta:
self.names.append(tag[0])
for tag in self.names:
self.values[tag]='0'
tk.Frame.__init__(self, perent)
frame = Frame(perent)
frame.grid(row=1, column=1)
canvas = Canvas(frame)
canvas.configure(scrollregion=(0,0,500,500), width=200, height=200)
myscrollbar = Scrollbar(frame, orient="vertical")
myscrollbar.grid(row=1, column=2, sticky="ns")
myscrollbar.config(command=canvas.yview)
canvas.config(yscrollcommand=myscrollbar.set)
R = 1
for key in self.values:
label = tk.Label(canvas, text=key + ':', font=AIR_FONT, bg=Gray, fg=Wight, borderwidth=0,
relief="solid")
value = tk.Label(canvas, text=self.values[key], font=AIR_FONT, bg=Gray, fg=Wight, borderwidth=0,
relief="solid")
label.grid(row=R, column=1, sticky="nsew")
value.grid(row=R, column=2, sticky="nsew")
R += 1
canvas.grid(row=1, column=1)
app = Midas_Screen()
app.mainloop()
The canvas can't scroll things added to the canvas with grid. The most common solution is to add a frame to the canvas with create_window, and then adding the labels to the frame.
See Adding a scrollbar to a group of widgets in Tkinter
So i made a few changes thanks and got it working :)
Bye using pack as you sugeted it works
#!Python
import matplotlib
matplotlib.use("TkAgg")
from matplotlib import style
import tkinter as tk
from tkinter import *
from YahooParser import Yahoo_Parser
TITLE_FONT = ("Helvetica", 10, "bold")
LARG_FONT = ("Helvetica", 12)
NORM_FONT = ("Helvetica", 10)
AIR_FONT = ("Arial", 10)
SMALL_FONT = ("Helvetica", 8)
style.use("ggplot")
#style.use("ggplot")
Gray = "#%02x%02x%02x" % (85, 85, 85)
Wight ="#%02x%02x%02x" % (220, 220, 220)
class Midas_Screen(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
# Title
tk.Tk.wm_title(self, "Midas Program")
tk.Tk.geometry(self,"500x400")
#tk.Tk.configure(self, background='black')
# This set the seting for the container
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 = {}
# Makes all the frames and stores them
for F in (HomePage,):
# You pass the container to your page function. this makes the frame
frame = F(container, self)
# this aligns the frame "nsew" = North, South etc
frame.grid(row=1, column=1, sticky="nsew")
# This uses the function as a key in the dic
self.frames[F] = frame
self.show_frame(HomePage)
def show_frame(self, key):
frame = self.frames[key]
frame.tkraise()
class HomePage(tk.Frame):
def __init__(self, perent, controller):
self.values = {}
for tag in range(20):
self.values['Text'+str(tag)+':']='0'
tk.Frame.__init__(self, perent)
def myfunction(event):
canvas.configure(scrollregion=canvas.bbox("all"), width=200, height=200)
canvas = Canvas(perent)
frame = Frame(canvas)
myscrollbar = Scrollbar(frame, orient="vertical", command=canvas.yview)
canvas.config(yscrollcommand=myscrollbar.set)
myscrollbar.pack(side=RIGHT, fill=Y)# sticky="ns")
canvas.grid(row=0, column=0, sticky="nw")
#canvas.pack(side=LEFT)
canvas.create_window((0, 0), window=frame, anchor='nw')
R = 1
for key in self.values:
row = Frame(frame)
label = tk.Label(row, text=key + ':', font=AIR_FONT, bg=Gray, fg=Wight, borderwidth=0,
relief="solid")
value = tk.Label(row, text=self.values[key], font=AIR_FONT, bg=Gray, fg=Wight, borderwidth=0,
relief="solid")
label.pack(side=LEFT, fill=X)
value.pack(side=LEFT,fill=X)
row.pack(side=TOP, fill=X)
R += 1
frame.bind("<Configure>", myfunction)
app = Midas_Screen()
app.mainloop()

python - calling plt.figure prevents Checkbutton from update - Tkinter

A GUI that works with different pages, one is a graph page using the animate function, and a second page should start a guide, the guide will depend on what you click in a checkbutton. I have created a post because I thought I was the checkbutton that was not well defined, but now i found that calling the f=plt.figure() is prevent the upgrade of the checkbutton.
See this code works for the Checkbutton: - Before the animate function .. But then the graphic update on the other page does not work since f is not defined in the animate function. If i put the animate function and f definition in the PageThree (GRAPHIC page) the update of the figure fails.
But when i allow the f=plt.figure() , graphic is fine, but checkbutton stays False all the time...
import matplotlib
from tkinter import *
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import tkinter as tk
from tkinter import ttk
import numpy as np
import matplotlib.animation as animation
from matplotlib import style
from matplotlib import pyplot as plt
from scipy.misc import *
import pandas as pd
import webbrowser
import subprocess
import csv
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
from os import startfile
from time import time
LARGE_FONT = ("Times", 11, "bold italic")
NORM_FONT = ("Helvetica", 9)
SMALL_FONT = ("Helvetica",7)
HELP_FONT=("Times", 9 , "bold")
pullDataMS=pd.read_table("test.raw.spectrum_table.tsv", header=1)
LevelMS=pullDataMS.groupby('msLevel')
rt=pullDataMS['rt']
TIC=pullDataMS['TIC']
MS1=LevelMS.get_group('ms1')
MS2=LevelMS.get_group('ms2')
### THIS CALL overplots the update? -.- ###
#f = plt.figure(facecolor="white")**
######################
def animate (i):
pullData=pd.read_table("InstrumentPerformance.txt", parse_dates=True,
dayfirst=True, index_col=1)
Names_In = ['Q1','Q2','Q3']
Inst=pullData.groupby('Instrument')
a = f.add_subplot(2,3,1)
a2 = f.add_subplot(2,3,2, sharex=a)
a3=f.add_subplot(2,3,3)
a4=f.add_subplot(2,3,4)
a5=f.add_subplot(2,3,5)
a7=f.add_subplot(2,6,11)
f.subplots_adjust(wspace=0.29)
a.clear()
a2.clear()
a3.clear()
a4.clear()
a5.clear()
a7.clear()
for Name in Names_In:
Q=Inst.get_group(Name)
y=Q['MS/MS recorded']
x=Q['Identified peptides']
a.plot(x, "o",label='['+Name+"]")
a.plot(x, 'k-', lw=0.7, label='_nolegend_')
a2.plot(y, 'o',label='['+Name+']')
a2.plot(y, 'k-', label='_nolegend_', lw=0.7)
a.xaxis.set_major_locator(mticker.MaxNLocator(5))
a.xaxis.set_major_formatter(mdates.DateFormatter("%d-%m-%Y"))
a.set_ylabel('# of unique peptide sequences')
a2.set_ylabel('# of MS/MS spectra')
a.legend(loc='upper left',fancybox=True, numpoints=1, shadow=True,prop={'size':9})
a2.legend(loc='upper left',fancybox=True, numpoints=1, shadow=True,prop={'size':9})
a.set_xlim(np.array([-20,20])+a.get_xlim())
a.set_ylim(np.array([0,2000])+a.get_ylim())
a2.set_xlim(np.array([-20,20])+a.get_xlim())
a2.set_ylim(np.array([0,5000])+a.get_ylim())
class PAL3_guide(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 = {}
for F in (StartPage,Tut01,PageThree):
frame = F(container, self)
self.frames[F] = frame
frame.grid(row=0, column=0, sticky="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, background="white")
button_PAL = ttk.Button(self, text="Setup Guide", command=lambda:controller.show_frame(Tut01))
button_PAL.pack()
button2 = ttk.Button(self, text="Graph Page 1",
command=lambda: controller.show_frame(PageThree))
button2.pack()
class Tut01(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
self.parent=parent
self.initUI()
def initUI(self):
self.var=BooleanVar()
cb=Checkbutton(self,text="show", variable=self.var, command=self.onClick)
cb.select()
cb.place(x=50,y=50)
def onClick(self):
if self.var.get()== True:
print("hi")
else:
print("buh")
class PageThree(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="GraphPage", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
toolbar=NavigationToolbar2TkAgg(canvas,self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH, expand=True)
app = PAL3_guide()
app.geometry("1280x920")
ani = animation.FuncAnimation(f, animate, interval=10000)
app.mainloop()
EDIT FOR MIXONE: yes i have tried to do something like :
def animate (f):
pullData=pd.read_table("InstrumentPerformance.txt", parse_dates=True,
dayfirst=True, index_col=1)
Names_In = ['Q1','Q2','Q3']
Inst=pullData.groupby('Instrument')
a = f.add_subplot(2,3,1)
a2 = f.add_subplot(2,3,2, sharex=a)...
...
and:
class PageThree(tk.Frame):
def __init__(self,parent,controller):
tk.Frame.__init__(self,parent)
label = tk.Label(self, text="GraphPage", font=LARGE_FONT)
label.pack(pady=10, padx=10)
button1 = ttk.Button(self, text="Back to Home",
command=lambda: controller.show_frame(StartPage))
button1.pack()
f=plt.figure()
ani = animation.FuncAnimation(f, animate(f), interval=10000)
canvas = FigureCanvasTkAgg(f, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
#toolbar=NavigationToolbar2TkAgg(canvas,self)
#toolbar.update()
#canvas._tkcanvas.pack(side=tk.TOP,fill=tk.BOTH, expand=True)
app = PAL3_guide()
app.geometry("1280x920")
app.mainloop()
In this case the Checkbutton works, but the figure is not updated but it is plotted in the beginning.

Resources