How to embed matplotlib graph into popup window using python Tkinter

I have a tkinter program that displays a matplotlib graph when I initially run it. I am having trouble, however, embedding a second matplotlib plot in my other popup window.

Ideally I want to be able to click a button and have a window with a matplotlib in it appear.

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import Tkinter as Tk

class Window():
    def __init__(self, master):
        self.master = master
        self.frame = Tk.Frame(master)
        self.button1 = Tk.Button(self.master, text = 'Open Graph Window', width = 25,command= self.new_window)
        self.f = Figure( figsize=(7, 6), dpi=80 )
        self.ax0 = self.f.add_axes( (0.05, .05, .50, .50), axisbg=(.75,.75,.10), frameon=True)

        self.frame = Tk.Frame(root)
        self.frame.pack(side=Tk.LEFT, fill=Tk.BOTH, expand=1)

        self.canvas = FigureCanvasTkAgg(self.f, master=self.frame)
        self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

    def new_window(self):
        self.newWindow = Tk.Toplevel(self.master) = Graph(self.newWindow)

class Graph():
    def __init__(self, master):
        self.master = master
        self.frame = Tk.Frame(master)
        self.f1 = Figure( figsize=(10, 9), dpi=80 )
        self.ax10 = self.f1.add_axes( (0.05, .05, .50, .50), axisbg=(.75,.75,.10), frameon=True)
        self.quitButton = Tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.canvas = FigureCanvasTkAgg(self.f1, master=self.master)

    def close_windows(self):

if __name__ == '__main__':
    root = Tk.Tk()
    app = Window(root)
    root.title( "MatplotLib with Tkinter" )

I have the code I thought should work in place to generate another matplotlib graph when I open another window. This doesnt work however. What can I do to get the second graph to appear when I click on the 'open window button'?

Any help would be greatly appreciated

1 answer

  • answered 2017-11-15 08:44 j_4321

    You have just forgotten to pack the canvas in the Graph class. Add the line

    self.canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

    in the __init__ method of Graph, and the graph should show up in the toplevel.