AttributeError: Image has no attribute 'open'

Viewed 1504

I'm new to learning the Tkinter Module that is built in Python. I was trying to build a simple Image Viewer GUI using pillow. I'm getting an Attribute Error here.

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

Here is my code:

from PIL import ImageTk,Image
from tkinter import *
base = Tk()
base.title("Image Viewer")
base.iconbitmap("download.ico")
img1 = ImageTk.PhotoImage(Image.open("download.png"))
label1 = Label(image = img1)
label1.grid(row = 0, column = 0, columnspan = 3)
base.mainloop()

I can't seem to find a fix for this and none of the solutions for similar questions on StackOverflow, work.

2 Answers
from tkinter import * 

this imports everything from tkinter, including Image:

Init signature: Image(imgtype, name=None, cnf={}, master=None, **kw)
Docstring:      Base class for images.
File:           [...]
Type:           type
Subclasses:     PhotoImage, BitmapImage

So, the Image module that you import earlier from PIL is overwritten.

you can

a) reverse the order:

from tkinter import *
from PIL import Image, ImageTk

b) import only that what you need from tkinter

from PIL import ImageTk, Image
from tkinter import Tk

c) import Image as something else:

from PIL import ImageTk
from PIL import Image as PILImage
from tkinter import * 

You can do onething try to use this snippet

import PIL.Image
import PIL.ImageTk
im = PIL.Image.open("download.png")
photo = PIL.ImageTk.PhotoImage(im)
Related