Yes - that Jake.
Yes - that Jake.

Reputation: 17129

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?

Upvotes: 3

Views: 6536

Answers (2)

Ken Roberts
Ken Roberts

Reputation: 47

It's very true what Meredith said you need to add that line for sure!

I would like to show you my image formatting and then compare it to yours and see if there any different, my code for a image is

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

And your code is

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

We are both using PIL with PhotoImage I can't help wondering are both ways correct? At this point in time I don't have enough knowledge to fully answer your PIL question but it is interesting to compare both codes as they are different. I can only suggest doing what I do when it comes to example codes people share with me, and that is "if mine don't work, try the example code and see if that fixes the code" when I find something that works I stick with it.

Would someone with more understanding of Tkinter please explane the workings of, How do I use PIL with Tkinter?

Knowledge is power so please share.

Upvotes: -1

Meredith L. Patterson
Meredith L. Patterson

Reputation: 4919

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

TK.Tk()

Upvotes: 6

Related Questions