numpy矩阵到tkinter画布 [英] Numpy Matrix to tkinter Canvas

查看:269
本文介绍了numpy矩阵到tkinter画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将Numpy矩阵作为位图显示到Tkinter画布中? 更准确地说,如何用矩阵中的内容填充PhotoImage?

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)

推荐答案

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

这篇关于numpy矩阵到tkinter画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆