From 1bf54c3d27e025a5d80a32e7ad15d5c6ce402396 Mon Sep 17 00:00:00 2001 From: PySimpleGUI Date: Mon, 27 Jan 2020 06:46:54 -0500 Subject: [PATCH] Demo - Matplotlib with toolbar embedded into GUI --- .../Demo_Matplotlib_Embedded_Toolbar.py | 81 +++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 DemoPrograms/Demo_Matplotlib_Embedded_Toolbar.py diff --git a/DemoPrograms/Demo_Matplotlib_Embedded_Toolbar.py b/DemoPrograms/Demo_Matplotlib_Embedded_Toolbar.py new file mode 100644 index 00000000..d593a22c --- /dev/null +++ b/DemoPrograms/Demo_Matplotlib_Embedded_Toolbar.py @@ -0,0 +1,81 @@ +import PySimpleGUI as sg +import numpy as np + +""" + Embedding the Matplotlib toolbar into your application + +""" + +# ------------------------------- This is to include a matplotlib figure in a Tkinter canvas +import matplotlib.pyplot as plt +from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk + + +def draw_figure_w_toolbar(canvas, fig, canvas_toolbar): + if canvas.children: + for child in canvas.winfo_children(): + child.destroy() + if canvas_toolbar.children: + for child in canvas_toolbar.winfo_children(): + child.destroy() + figure_canvas_agg = FigureCanvasTkAgg(fig, master=canvas) + figure_canvas_agg.draw() + toolbar = Toolbar(figure_canvas_agg, canvas_toolbar) + toolbar.update() + figure_canvas_agg.get_tk_widget().pack(side='right', fill='both', expand=1) + + +class Toolbar(NavigationToolbar2Tk): + def __init__(self, *args, **kwargs): + super(Toolbar, self).__init__(*args, **kwargs) + + +# ------------------------------- PySimpleGUI CODE + +layout = [ + [sg.T('Graph: y=sin(x)')], + [sg.B('Plot'), sg.B('Exit')], + [sg.T('Controls:')], + [sg.Canvas(key='controls_cv')], + [sg.T('Figure:')], + [sg.Column( + layout=[ + [sg.Canvas(key='fig_cv', + # it's important that you set this size + size=(400 * 2, 400) + )] + ], + background_color='#DAE0E6', + pad=(0, 0) + )], + [sg.B('Alive?')] + +] + +window = sg.Window('Graph with controls', layout) + +while True: + event, values = window.read() + print(event, values) + if event in (None, 'Exit'): # always, always give a way out! + break + elif event is 'Plot': + # ------------------------------- PASTE YOUR MATPLOTLIB CODE HERE + plt.figure(1) + fig = plt.gcf() + DPI = fig.get_dpi() + # ------------------------------- you have to play with this size to reduce the movement error when the mouse hovers over the figure, it's close to canvas size + fig.set_size_inches(404 * 2 / float(DPI), 404 / float(DPI)) + # ------------------------------- + x = np.linspace(0, 2 * np.pi) + y = np.sin(x) + plt.plot(x, y) + plt.title('y=sin(x)') + plt.xlabel('X') + plt.ylabel('Y') + plt.grid() + + # ------------------------------- Instead of plt.show() + draw_figure_w_toolbar(window['fig_cv'].TKCanvas, fig, window['controls_cv'].TKCanvas) + +window.close()