PySimpleGUI Matplotlib集成
当从Python shell中使用Matplotlib时,绘图被显示在一个默认的窗口中。 backend_tkagg 模块对于在Tkinter中嵌入绘图非常有用。
PySimpleGUI中的Canvas元素有TKCanvas方法,可以返回原始TKinter的Canvas对象。它被交给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
通过调用PySimpleGUI.Canvas对象的TkCanvas属性获得Canvas。
layout = [
[psg.Text('Plot test')],
[psg.Canvas(key='-CANVAS-')],
[psg.Button('Ok')]
]
通过调用上述函数绘制图形。将Canvas对象和fifure对象传给它。
fig_canvas_agg = draw_figure(window['-CANVAS-'].TKCanvas, fig)
例子:绘制一个正弦波线图
以下是完整的代码-
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()
生成的图表如下-