You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将matplotlib图表嵌入PySimpleGUI文件浏览窗口并新增第二CSV绘图功能

解决方案

实现思路

  • 调用Matplotlib的TkAgg后端,将绘图对象直接渲染到PySimpleGUI的Canvas控件中,完全取消独立弹窗
  • 布局拆分两组独立的文件选择模块+绘图区域,适配双CSV的使用需求
  • 绑定文件选择事件,选中CSV后自动读取数据并刷新对应区域的图表

完整实现代码

import pandas as pd
import PySimpleGUI as sg
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# 配置Matplotlib适配PySimpleGUI
plt.rcParams['font.sans-serif'] = ['SimHei'] # 可选:解决中文显示问题
plt.rcParams['axes.unicode_minus'] = False

# 绘图渲染到Canvas的工具函数
def draw_fig(canvas, fig):
    fig_canvas = FigureCanvasTkAgg(fig, master=canvas)
    fig_canvas.draw()
    fig_canvas.get_tk_widget().pack(fill='both', expand=True)
    return fig_canvas

# 窗口布局定义
layout = [
    [sg.Text('第一个CSV文件:'), sg.Input(key='-FILE1-', enable_events=True), sg.FileBrowse('选择文件', file_types=(("CSV文件", "*.csv"), ("所有文件", "*.*")))],
    [sg.Canvas(key='-CANVAS1-', size=(700, 380))],
    [sg.HorizontalSeparator()],
    [sg.Text('第二个CSV文件:'), sg.Input(key='-FILE2-', enable_events=True), sg.FileBrowse('选择文件', file_types=(("CSV文件", "*.csv"), ("所有文件", "*.*")))],
    [sg.Canvas(key='-CANVAS2-', size=(700, 380))],
    [sg.Push(), sg.Button('退出'), sg.Push()]
]

# 初始化窗口
window = sg.Window('CSV数据可视化工具', layout, finalize=True, resizable=True)

# 存储两个画布的绘图对象,避免重复渲染
fig_agg1, fig_agg2 = None, None

# 事件循环
while True:
    event, values = window.read()
    if event in (sg.WIN_CLOSED, '退出'):
        break
    
    # 第一个CSV文件选中处理
    if event == '-FILE1-':
        file_path = values['-FILE1-']
        if not file_path:
            continue
        # 读取CSV数据
        df = pd.read_csv(file_path)
        print('第一个数据集统计描述:\n', df.describe())
        # 绘图
        fig1, ax1 = plt.subplots(figsize=(7, 3.5))
        ax1.plot(df)
        ax1.set_xlabel('Milliseconds')
        ax1.set_ylabel('Percentage of score')
        ax1.grid()
        # 保存图片,可修改为自己的路径
        plt.savefig(r"C:\Users\Vatsan\Documents\Fanuc\Result1.jpeg", dpi=300, bbox_inches='tight')
        # 清空旧画布再渲染新图
        if fig_agg1:
            fig_agg1.get_tk_widget().destroy()
        fig_agg1 = draw_fig(window['-CANVAS1-'].TKCanvas, fig1)
    
    # 第二个CSV文件选中处理
    if event == '-FILE2-':
        file_path = values['-FILE2-']
        if not file_path:
            continue
        # 读取CSV数据
        df = pd.read_csv(file_path)
        print('第二个数据集统计描述:\n', df.describe())
        # 绘图
        fig2, ax2 = plt.subplots(figsize=(7, 3.5))
        ax2.plot(df)
        ax2.set_xlabel('Milliseconds')
        ax2.set_ylabel('Percentage of score')
        ax2.grid()
        # 保存图片,可修改为自己的路径
        plt.savefig(r"C:\Users\Vatsan\Documents\Fanuc\Result2.jpeg", dpi=300, bbox_inches='tight')
        # 清空旧画布再渲染新图
        if fig_agg2:
            fig_agg2.get_tk_widget().destroy()
        fig_agg2 = draw_fig(window['-CANVAS2-'].TKCanvas, fig2)

window.close()
plt.close('all')

注意事项

  • 运行前确保已安装所有依赖:pip install pandas matplotlib pysimplegui
  • 可根据需求调整画布尺寸、坐标轴标注、图表样式等参数
  • 若不需要控制台输出统计描述,可将print语句删除,或新增Output控件将输出展示到窗口内

内容的提问来源于stack exchange,提问作者Srivatsan M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 19:45:03