Why does Pillow raise AttributeError 'Image' has no attribute 'open' when I use tkinter?
Asked Answered
C

2

0

I have been trying to create this piece that changes all of the white pixels in an image to the hex value of the current background but I cannot get past the error:

AttributeError: type object 'Image' has no attribute 'open'

I have installed many of the PIP/pillow/PIL packages and I'm not even sure if this is the problem.

This is my code that reproduces the error:

import tkinter as tk
import sys
from PIL import Image
from datetime import datetime
from tkinter import *
import time

# ...

# List of image filenames
images = ["personal progress.png", "settings.png", "stopwatch.png"]

# Loop through each image
for img_filename in images:
    # Load the image using PIL
    img = Image.open(img_filename)  # AttributeError raised here
Coben answered 7/8, 2023 at 11:52 Comment(2)
Please show import statementCleave
From PIL import ImageCoben
O
3

You have conflicting imports.

Both of these imports

from PIL import Image

from tkinter import *

attempt to bind the global variable Image. The first one binds it to the PIL.Image module, and then the re-second binds it to the tkinter.Image type.

To fix this, remove the glob import from tkinter import * and access tkinter items through your import tkinter as tk import.

In the future, you might want to avoid glob imports altogethor to avoid this kind of issue. See also Why is import * bad?

Ominous answered 7/8, 2023 at 14:19 Comment(0)
O
-1

The error

AttributeError: type object 'Image' has no attribute 'open'

says that you're trying to call open on a type object (not the module object you'd expect).

Without seeing your actual imports, I can only guess that type is the PIL.Image.Image class that Pillow provides. The actual open function is a global function on the Image module PIL.Image.

Most likely, you need to change an import from

from PIL.Image import Image

to

from PIL import Image
Ominous answered 7/8, 2023 at 11:59 Comment(2)
I should have included the import statements but regardless this is what my imports were anyway.Coben
@unreal8usher Do edit your question to include all imports. In particular, are you using any glob imports?Ominous

© 2022 - 2024 — McMap. All rights reserved.