- PySimpleGUI Tutorial
- PySimpleGUI - Home
- PySimpleGUI - Introduction
- PySimpleGUI - Environment Setup
- PySimpleGUI - Hello World
- PySimpleGUI - Popup Windows
- PySimpleGUI - Window Class
- PySimpleGUI - Element Class
- PySimpleGUI - Events
- PySimpleGUI - Menubar
- PySimpleGUI - Matplotlib Integration
- PySimpleGUI - Working with PIL
- PySimpleGUI - Debugger
- PySimpleGUI - Settings
- PySimpleGUI Useful Resources
- PySimpleGUI - Quick Guide
- PySimpleGUI - Useful Resources
- PySimpleGUI - Discussion
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 对象和 fiture 对象传递给它。
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()
生成的图表如下 -