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
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With