PySimpleGUI/PySimpleGUIWeb/Demo Programs/Web_Matplotlib_Simple.py

59 lines
1.4 KiB
Python
Raw Normal View History

2020-07-06 15:18:59 +00:00
import PySimpleGUIWeb as sg
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasAgg
import matplotlib.figure
import matplotlib.pyplot as plt
2020-07-06 15:18:59 +00:00
import io
def create_figure():
# ------------------------------- START OF YOUR MATPLOTLIB CODE -------------------------------
fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
return fig
2020-07-07 18:41:30 +00:00
def draw_figure(element, fig):
"""
Draws the previously created "figure" in the supplied Image Element
:param element: an Image Element
2020-07-07 18:41:30 +00:00
:param fig: a Matplotlib figure
:return: The figure canvas
"""
plt.close('all') # erases previously drawn plots
2020-07-06 15:18:59 +00:00
canv = FigureCanvasAgg(fig)
buf = io.BytesIO()
canv.print_figure(buf, format='png')
if buf is None:
return None
buf.seek(0)
element.update(data=buf.read())
return canv
2020-07-06 15:18:59 +00:00
def main():
layout = [
[sg.T('Matplotlib Example', font='Any 20')],
[sg.Image(key='-IMAGE-')],
[sg.B('Draw'), sg.B('Exit')],
]
window = sg.Window('Title', layout)
while True:
event, values = window.read()
if event == 'Exit' or event == sg.WIN_CLOSED:
break
if event == 'Draw':
2020-07-07 18:41:30 +00:00
draw_figure(window['-IMAGE-'], create_figure())
2020-07-06 15:18:59 +00:00
window.close()
if __name__ == "__main__":
main()