Pysimplegui 简明教程

PySimpleGUI - Matplotlib Integration

当在 Python shell 中使用 Matplotlib 时,图表将显示在一个默认窗口中。 backend_tkagg 模块可用于将图表嵌入到 Tkinter 中。

PySimpleGUI 中的 Canvas 元素具有返回原始 TKinter Canvas 对象的 TKCanvas 方法。在 backend_tkagg 模块中将其提供给 FigureCanvasTkAgg() 函数以绘制图形。

首先,我们需要使用 Figure() 类和一个绘图创建一个图形对象。我们将绘制一个显示正弦波的简单图表。

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))

定义一个函数,在画布上绘制 matplotlib 图形对象

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

通过调用其 TkCanvas 属性,从 PySimpleGUI.Canvas 对象获取画布。

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

调用上述函数绘制图形。将画布对象和图形对象传递给它。

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

Example: Draw a Sinewave Line graph

以下是完整代码 −

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import
FigureCanvasTkAgg
import PySimpleGUI as sg
import matplotlib
matplotlib.use('TkAgg')
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))
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('Matplotlib In PySimpleGUI', layout, size=(715, 500), finalize=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()

生成的图表如下 −

sinewave graph