概要
- 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()
改訂履歴
- 2026.03.20
初回投稿。とりあえず忘れないように作成。