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

如何在Pyglet窗口中嵌入Matplotlib绘图 解决Python3兼容问题

故障根因

你怀疑的位置完全正确,问题的核心是Python3对字符串和字节流做了严格区分:

  • io.StringIO仅支持存储Unicode文本数据,而Matplotlib画布输出的原始图像是二进制字节流,写入StringIO会直接抛出类型不匹配错误。
  • 原代码中的"是HTML转义后的双引号,实际编写代码时需要替换为普通双引号。
修复后的完整可运行代码
import pyglet
import io
import numpy as np

from matplotlib.figure import Figure
from matplotlib.backends.backend_agg import FigureCanvasAgg


def render_figure(fig):
    w, h = fig.get_size_inches()
    dpi_res = fig.get_dpi()
    w, h = int(np.ceil(w * dpi_res)), int(np.ceil(h * dpi_res))

    canvas = FigureCanvasAgg(fig)
    pic_data = io.BytesIO()  # 替换为BytesIO存储二进制流
    canvas.print_raw(pic_data, dpi=dpi_res)
    return pyglet.image.ImageData(w, h, "RGBA", pic_data.getvalue(), -4 * w)


def draw_figure(fig):
    X = np.linspace(-6, 6, 1024)
    Y = np.sinc(X)

    ax = fig.add_subplot(111)
    ax.plot(X, Y, lw=2, color="k")


# 可以把fullscreen=True改为width=800, height=600方便测试
window = pyglet.window.Window(fullscreen=True)
dpi_res = min(window.width, window.height) / 10
fig = Figure((window.width / dpi_res, window.height / dpi_res), dpi=dpi_res)

draw_figure(fig)
image = render_figure(fig)


@window.event
def on_draw():
    window.clear()
    image.blit(0, 0)


pyglet.app.run()
运行前置依赖

执行以下命令安装所需库即可:
pip install pyglet numpy matplotlib

内容的提问来源于stack exchange,提问作者Philippe Maisonneuve

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:39:03