Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use PIL with Tkinter?

I'm missing something at a very 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've confirmed the file is present and can be opened in an image editor and also that it can be displayed using im.show(). What am I missing?

like image 719
Yes - that Jake. Avatar asked Feb 01 '26 13:02

Yes - that Jake.


1 Answers

Tkinter has to be instantiated before you call ImageTk.PhotoImage():

TK.Tk()
like image 90
Meredith L. Patterson Avatar answered Feb 04 '26 02:02

Meredith L. Patterson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!