0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonのTkinterでMatplotlibを画像として表示する(io.BytesIO使用)

0
Posted at

概要

  • MatplotlibをtkinterのGui表示で使いたい。
  • tkinterならFigureCanvasTkAggを使う方法が一般的だと思うけど(参考)、他のGuiライブラリ(Flet、PySimpleGUIなど)でも使える汎用的な方法として、画像にして表示する方法を確認。
  • 発展させて計測器の測定でリアルタイムに更新するものを目指したい。
  • なんかいつも同じようなことをwebで検索してるので、メモとして残しておきたかった。

環境

  • Win11 Home (64bit 23H2)
  • Python:3.12.11
  • Matplotlib:3.10.7

ソースコード1

  • これで動くことは確認済。
test_01.py
# -*- coding: utf-8 -*-

import tkinter as tk
import matplotlib.pyplot as plt
import io
from PIL import Image, ImageTk


def create_plot_image():

    fig, ax = plt.subplots()
    ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
    ax.set_title("Matplotlib Plot in Tkinter")
    
    buf = io.BytesIO()
    plt.savefig(buf, format="png")
    buf.seek(0)

    plt.close(fig) 

    pil_image = Image.open(buf)

    tk_image = ImageTk.PhotoImage(pil_image)

    buf.close()
    
    return tk_image


def main():

    root = tk.Tk()
    root.title("Tkinter Matplotlib BytesIO Example")

    plot_image = create_plot_image()

    canvas = tk.Canvas(root, width=plot_image.width(), height=plot_image.height())
    canvas.place(x=0, y=0)
    canvas.create_image(0, 0, image=plot_image, anchor=tk.NW)

    root.mainloop()


if __name__ == "__main__":
    main()

ソースコード2

  • 「ソースコード1」のcanvasをlabelにしただけ。
  • これで動くことは確認済。
test_02.py
# -*- coding: utf-8 -*-

import tkinter as tk
import matplotlib.pyplot as plt
import io
from PIL import Image, ImageTk


def create_plot_image():

    fig, ax = plt.subplots()
    ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
    ax.set_title("Matplotlib Plot in Tkinter")
    
    buf = io.BytesIO()
    plt.savefig(buf, format="png")
    buf.seek(0)

    plt.close(fig) 

    pil_image = Image.open(buf)

    tk_image = ImageTk.PhotoImage(pil_image)

    buf.close()
    
    return tk_image


def main():

    root = tk.Tk()
    root.title("Tkinter Matplotlib BytesIO Example")

    plot_image = create_plot_image()

    label = tk.Label(root, image=plot_image)
    label.image = plot_image    # ※1これ入れたほうがいいみたい
    label.pack()

    root.mainloop()


if __name__ == "__main__":
    main()

※1 tkinterで画像が表示されない現象について

改訂履歴

  • 2026.03.20
    初回投稿。とりあえず忘れないように作成。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?