English 中文(简体)
PySimpleGUI - Matplotlib Integration
  • 时间:2025-02-05

PySimpleGUI - Matplotpb Integration


Previous Page Next Page  

When Matplotpb is used from Python shell, the plots are displayed in a default window. The backend_tkagg module is useful for embedding plots in Tkinter.

The Canvas element in PySimpleGUI has TKCanvas method that returns original TKinter s Canvas object. It is given to the FigureCanvasTkAgg() function in the backend_tkagg module to draw the figure.

First, we need to create the figure object using the Figure() class and a plot to it. We shall draw a simple plot showing sine wave.


fig = matplotpb.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))

Define a function to draw the matplotpb figure object on the canvas


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 , expand=1)
   return figure_canvas_agg

Obtain the Canvas from PySimpleGUI.Canvas object by calpng its TkCanvas property.


layout = [
   [psg.Text( Plot test )],
   [psg.Canvas(key= -CANVAS- )],
   [psg.Button( Ok )]
]

Draw the figure by calpng the above function. Pass the Canvas object and fifure object to it.


fig_canvas_agg = draw_figure(window[ -CANVAS- ].TKCanvas, fig)

Example: Draw a Sinewave Line graph

The complete code is given below −


import matplotpb.pyplot as plt
import numpy as np
from matplotpb.backends.backend_tkagg import
FigureCanvasTkAgg
import PySimpleGUI as sg
import matplotpb
matplotpb.use( TkAgg )
fig = matplotpb.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))
def draw_figure(canvas, figure):
   tkcanvas = FigureCanvasTkAgg(figure, canvas)
   tkcanvas.draw()
   tkcanvas.get_tk_widget().pack(side= top , fill= both , expand=1)
   return tkcanvas
layout = [[sg.Text( Plot test )],
   [sg.Canvas(key= -CANVAS- )],
   [sg.Button( Ok )]]
window = sg.Window( Matplotpb In PySimpleGUI , layout, size=(715, 500), finapze=True, element_justification= center , font= Helvetica 18 )

# add the plot to the window
tkcanvas = draw_figure(window[ -CANVAS- ].TKCanvas, fig)
event, values = window.read()
window.close()

The generated graph is as follows −

Sinewave Graph Advertisements