Numpy Matrix to tkinter Canvas

时光怂恿深爱的人放手 提交于 2020-01-23 03:17:33

问题


How to display a Numpy matrix, as a bitmap, into a Tkinter canvas? More precisely, how to fill a PhotoImage with content from a matrix?

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

回答1:


Here is working solution, slightly modified to make it work (some function was deprecated) and to simplify it to keep only the necessary part. We have to use Image.frombytes(...) to read the data in the numpy matrix.

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()


来源:https://stackoverflow.com/questions/41504375/numpy-matrix-to-tkinter-canvas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!