2017-01-06 7 views
1

ナンキー行列をビットマップとしてTkinterキャンバスに表示するにはどうすればいいですか? より正確には、PhotoImageの内容をマトリックスから埋め込む方法は?ナンキー行列とtkinterキャンバス

photo = ImageTk.PhotoImage(...) 
self.canvas.create_image(0,0,image=photo,anchor=Tkinter.NW) 

答えて

0

Here少しそれを動作させるために(いくつかの機能が廃止されました)と、必要な部分のみを保つために、それを簡単にするために変更され、作業のソリューションです。 numpy行列のデータを読み取るには、Image.frombytes(...)を使用する必要があります。

import Tkinter 
from PIL import Image, ImageTk 
import numpy 

class mainWindow(): 
    def __init__(self): 
     self.root = Tkinter.Tk() 
     self.frame = Tkinter.Frame(self.root, width=500, height=400) 
     self.frame.pack() 
     self.canvas = Tkinter.Canvas(self.frame, width=500,height=400) 
     self.canvas.place(x=-2,y=-2) 
     data=numpy.array(numpy.random.random((400,500))*100,dtype=int) 
     self.im=Image.frombytes('L', (data.shape[1],data.shape[0]), data.astype('b').tostring()) 
     self.photo = ImageTk.PhotoImage(image=self.im) 
     self.canvas.create_image(0,0,image=self.photo,anchor=Tkinter.NW) 
     self.root.update() 
     self.root.mainloop() 

mainWindow() 
+1

あなたは何に対する答え@Basj 'イム= Image.fromarray(データ)' – nitzel

+0

でさえ速くそこに着くことができますか?疑問はない。しかし、ndarrayを文字列に変換する必要はありません。関連: http://pillow.readthedocs.io/ja/3.1.x/reference/Image.html#PIL.Image.fromarray – nitzel

+1

あなたの答えを改善するために、 'self.im = Image.frombytes( 'L'、 (data.shape [1]、data.shape [0])、data.astype( 'b')tostring()) 'と' self.im = Image.fromarray(data) 'ああ、実際には必要ありません'im'は' self'のメンバーになります。それ以外の場合はガベージコレクションが行われる可能性があるので、 '写真'への参照を保持することは唯一の重要な部分です。さらに、これらの参照を、例えば、次のように格納することが標準的であると思われる。 'self.canvas._foo' あなたのスナップは確かに私を助けました。 – nitzel

関連する問題