Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display an image from a numpy array in tkinter?

Tags:

python

tkinter

The following short code is meant to create an array with numpy, convert it into an image object with PIL and then insert into a canvas on a tkinter window.

from tkinter import *
from PIL import Image

root = Tk()
array = np.ones((40,40))*150
img = Image.fromarray(array)
canvas = Canvas(root,width=300,height=300)
canvas.pack()
canvas.create_image(20,20,anchor=NW,image=img)

root.mainloop()

This throws the error:

TclError: image "<PIL.Image.Image image mode=F size=40x40 at 0x7F42D3BC3290>" doesn't exist
like image 839
hirschme Avatar asked Nov 14 '18 21:11

hirschme


People also ask

How do I display an image in Python GUI?

To display an image requires the use of Image and ImageTk imported from the Python Pillow (aka PIL) package. A label widget can display either PhotoImage or BitmapImage objects: The PhotoImage class is used to display grayscale or true color icons, as well as images in labels.

How do I load an image into a Numpy array?

Using OpenCV Libraryimread() function is used to load the image and It also reads the given image (PIL image) in the NumPy array format. Then we need to convert the image color from BGR to RGB. imwrite() is used to save the image in the file.


1 Answers

You need to use PhotoImage from ImageTk.

Do this instead:

import tkinter as tk
import numpy as np
from PIL import Image, ImageTk

root = tk.Tk()

array = np.ones((40,40))*150
img =  ImageTk.PhotoImage(image=Image.fromarray(array))

canvas = tk.Canvas(root,width=300,height=300)
canvas.pack()
canvas.create_image(20,20, anchor="nw", image=img)

root.mainloop()
like image 77
Mike - SMT Avatar answered Oct 17 '22 09:10

Mike - SMT