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

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

问题描述:

我试图在matplotlib中生成一个图,将它保存到内存中的图像,然后将该图像放在tkinter.Canvas上。将matplotlib图保存到内存并放在tkinter画布上

我的代码如下:

%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

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

+0

也做到了,谢谢! –