PIL has no ImageTk attribute

Viewed 1582

why would this work:

...
from PIL import Image, ImageTk
.... 
img = ImageTk.PhotoImage(Image.open("One.jpg"))
...

but this

...
import PIL as p
.... 
img = p.ImageTk.PhotoImage(p.Image.open("One.jpg"))
...

tells me module 'PIL' has no attribute 'ImageTk'?

I thought that I could import PIL as p then use anything in PIL in my code as long as it's preceded by p.

I'd like to avoid using from PIL import Image, ImageTk because I like to have the context of which modules bits of code come from.

1 Answers

PIL's __init__.py is an empty stub as is common. It will not import all modules.

So when you try: from PIL import ImageTk it search in the PIL package folder and finds the file ImageTk.py and imports that.

But when you try: PIL.ImageTk you are actually doing an attribute lookup on the PIL module.

To avoid confusion you could do:

from PIL import Image as Pil_image, ImageTk as Pil_imageTk

So that you give the class a name thats tells you where it comming from.

Related