How to use PIL with Tkinter?

I am missing something at the most basic level when it comes to loading an image using PIL and displaying it in a window created by Tkinter. The simplest form of what I'm trying to do is:

import Tkinter as TK
from PIL import Image, ImageTk

im = Image.open("C:\\tinycat.jpg")
tkIm = ImageTk.PhotoImage(im)
tkIm.pack()
TK.mainloop()

When I try to run the code above, I get the following:

RuntimeError: Too early to create image
Exception AttributeError: "PhotoImage instance has no attribute 
'_PhotoImage__photo'" in <bound method PhotoImage.__del__ of 
<PIL.ImageTk.PhotoImage instance at 0x00C00030>> ignored

I confirmed that the file is present and can be opened in the image editor, and also that it can be displayed using im.show (). What am I missing?

+3
source share
2 answers

Tkinter must be created before calling ImageTk.PhotoImage ():

TK.Tk()
+6
source

It is very true that Meredith said that you need to add this line for sure!

, , ,

master.image = PhotoImage(file="Banditlogo.gif")
w = Label(master, image=master.image)
w.photo = master
w.pack()

im = Image.open("C:\\tinycat.jpg")
tkIm = ImageTk.PhotoImage(im)
tkIm.pack()

PIL PhotoImage , ? , PIL, , . , , , , " , , ", -, , .

- Tkinter, , , PIL Tkinter?

- , , , .

-1

Source: https://habr.com/ru/post/1714453/


All Articles