将matplotlib图保存到内存并放置在tkinter画布上

时间:2017-04-22 21:41:42

标签: python canvas matplotlib

我正在尝试在matplotlib中生成一个情节,将其保存到内存中的图像,然后将该图像放在tkinter.Canvas上。

我的代码如下:

%matplotlib inline
import io
from PIL import Image
import matplotlib.pyplot as plt
import tkinter

gr_data = ([1, 2])
plt.figure()
plt.plot(gr_data)
plt.title("test")

buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)

window = tkinter.Tk()
window.title('Test')
window.geometry('500x500-200+100')

photo = tkinter.PhotoImage(file=im)

can = tkinter.Canvas(window, height=480, width=600, bg='light blue')
can.pack()
can.create_image(0,0, image=photo, anchor='nw')
buf.close()
window.mainloop()

我收到以下错误:

---------------------------------------------------------------------------
TclError                                  Traceback (most recent call last)
<ipython-input-15-484d38f49c92> in <module>()
     19 window.geometry('500x500-200+100')
     20 
---> 21 photo = tkinter.PhotoImage(file=im)
     22 
     23 can = tkinter.Canvas(window, height=480, width=600, bg='light blue')

C:\Users\Kevin\dev.local\python\Anaconda3\lib\tkinter\__init__.py in __init__(self, name, cnf, master, **kw)
   3401         Valid resource names: data, format, file, gamma, height, palette,
   3402         width."""
-> 3403         Image.__init__(self, 'photo', name, cnf, master, **kw)
   3404     def blank(self):
   3405         """Display a transparent image."""

C:\Users\Kevin\dev.local\python\Anaconda3\lib\tkinter\__init__.py in __init__(self, imgtype, name, cnf, master, **kw)
   3357                 v = self._register(v)
   3358             options = options + ('-'+k, v)
-> 3359         self.tk.call(('image', 'create', imgtype, name,) + options)
   3360         self.name = name
   3361     def __str__(self): return self.name

TclError: couldn't open "<PIL.PngImagePlugin.PngImageFile image mode=RGBA size=432x288 at 0x294D8E70E80>": no such file or directory

我发现的所有其他帖子似乎都表明我所做的是正确的,但它不起作用,任何想法?我在Python 3中。

1 个答案:

答案 0 :(得分:3)

代替photo = tkinter.PhotoImage(file=im),您可以使用

from PIL import ImageTk
photo = ImageTk.PhotoImage(im)

完整代码:

import io
from PIL import ImageTk, Image
import matplotlib.pyplot as plt
import tkinter #import Tkinter as tkinter # for py2.7

gr_data = ([1, 2])
plt.figure()
plt.plot(gr_data)
plt.title("test")

buf = io.BytesIO()
plt.savefig(buf, format='png')
buf.seek(0)
im = Image.open(buf)

window = tkinter.Tk()
window.title('Test')
window.geometry('500x500-200+100')

photo = ImageTk.PhotoImage(im)

can = tkinter.Canvas(window, height=480, width=600, bg='light blue')
can.pack()

can.create_image(0,0, image=photo, anchor='nw')
buf.close()
window.mainloop()

enter image description here