Sergey
Sergey

Reputation: 1001

Alternative way of connecting to PIL library?

Usually the library PIL is connected as follows:

from PIL import ImageTk, Image 

I would like to connect it this way:

import PIL

but my version does not work. Here's the code:

import os, sys
import tkinter
import PIL

main = tkinter.Tk()

catalogImg1 = 'imgs'
nameImg1 = 'n.jpg'
pathImg1 = os.path.join(catalogImg1, nameImg1)

openImg = PIL.Image.open(pathImg1)

renderImg = PIL.ImageTk.PhotoImage(openImg)
tkinter.Label(main, image=renderImg).pack()

main.mainloop()

The error message is:

Traceback (most recent call last): File "C:\Python33\projects\PIL_IMAGETK\ImageTK_photoimage - копия.py", line 11, in openImg = PIL.Image.open(pathImg1) AttributeError: 'module' object has no attribute 'Image'

Upvotes: 0

Views: 368

Answers (2)

Sunny Nanda
Sunny Nanda

Reputation: 2382

This is because, Image is a submodule within the PIL package i.e. It is not a function or class. Importing a package does not automatically import its submodules.

If you want to use the PIL namespace, you can import the module as follows:

import PIL.Image
openImg = PIL.Image.open(pathImg1)

If you want to import all the submodules of PIL, you can do the following

from PIL import *
openImg = Image.open(pathImg1)

Upvotes: 1

falsetru
falsetru

Reputation: 369044

Importing a package (PIL) does not automatically import subpackages, submodules (PIL.Image, PIL.ImageTk). (Unless the package itself do it).

Explicitly import the submodules.

Replace following line:

import PIL

with:

import PIL.Image
import PIL.ImageTk

Upvotes: 2

Related Questions