如何将 Numpy 矩阵作为位图显示到 Tkinter 画布中?更准确地说,如何填写PhotoImage
来自矩阵的内容?
photo = ImageTk.PhotoImage(...)
self.canvas.create_image(0,0,image=photo,anchor=Tkinter.NW)
Here http://www.swharden.com/wp/2010-06-24-fast-tk-pixelmap-generation-from-2d-numpy-arrays-in-python/是可行的解决方案,稍作修改即可使其正常工作(某些功能已被弃用)并简化它以仅保留必要的部分。我们必须使用Image.frombytes(...)
读取 numpy 矩阵中的数据。
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()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)