'How can I open an image in Python?

I have looked at a lot of tutorials tried them all, but nothing seemed to work through Pygame, PIL, Tkinter. it could be because of me of course, cause Im a greenie...

from Tkinter import *

root = Tk()
photo = PhotoImage(file="too.jpg")
label = Label(root, image=photo)
label.pack()

root.mainloop()


Solution 1:[1]

Your code is correct but it won't work because of the jpgfile.

If you want to use the PhotoImage class you can only read read GIF and PGM/PPM images from files (see docs).

For other file formats you can use the Python Imaging Library (PIL).

Here's your example using PIL:

from Tkinter import *
from PIL import Image, ImageTk

root = Tk()
image = Image.open("too.jpg")
photo = ImageTk.PhotoImage(image)

label = Label(image=photo)
label.image = photo  # keep a reference!
label.pack()

root.mainloop()

The line label.image = photo is necessary if you want to avoid your image getting garbage-collected.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1