Issue
I have the issue that if I try to update a canvas in PySimpleGUI the application instead appends the new plot below the old one. Trigering the 'Generate Plot' from the code below leads to the output at the bottom. Instead of Appending the plot I expected it to replace it.
import PySimpleGUI as sg
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def draw_figure(canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both')
return figure_canvas_agg
# Define the layout of the GUI
layout = [
[sg.Button('Generate Plot')],
[sg.Canvas(size=(100, 100),key='canvas')],
[sg.Button('Exit')]
]
window = sg.Window('Time Series Plot', layout, finalize=True)
# Event loop
while True:
event, values = window.read()
x = np.linspace(1, 50)
y = np.random.randn(50)
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event in ['Generate Plot']:
fig, ax =plt.subplots()
# Create a time series plot
ax.plot(x, y)
# Embed the Matplotlib plot into the PySimpleGUI window
draw_figure(window['canvas'].TKCanvas, fig)
# Close the window
window.close()
Solution
It will create a new canvas under Canvas element when each time you call FigureCanvasTkAgg(figure, canvas)
, and they will be packed from top to bottom, not overlapped.
Call figure_canvas_agg.draw()
if you just want to update the figure.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import PySimpleGUI as sg
def draw_figure(canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top', fill='both')
return figure_canvas_agg
layout = [
[sg.Button('Generate Plot')],
[sg.Canvas(size=(100, 100),key='canvas')],
[sg.Button('Exit')]
]
window = sg.Window('Time Series Plot', layout, finalize=True)
fig, figure_canvas_agg = None, None
while True:
event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Exit':
break
if event == 'Generate Plot':
if fig is None:
fig, ax = plt.subplots()
else:
ax.cla()
x = np.linspace(1, 50)
y = np.random.randn(50)
ax.plot(x, y)
if figure_canvas_agg is None:
figure_canvas_agg = draw_figure(window['canvas'].TKCanvas, fig)
else:
figure_canvas_agg.draw()
window.refresh()
window.move_to_center()
window.close()
Answered By - Jason Yang
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.