6

I've spent some time looking online and so far haven't found anything that answers this without using PIL, which i can't get to work is there another way to do this simply?

LuGibs
  • 190
  • 1
  • 1
  • 14
  • Are you using PIL or [Pillow](https://pillow.readthedocs.org/)? – MattDMo Jan 26 '16 at 21:32
  • what means `i can't get to work` ? Do you can't install ? Do you get error message ? image disappears (very common problem) ? – furas Jan 26 '16 at 21:42
  • Possible duplicate of [Cannot Display an Image in Tkinter](https://stackoverflow.com/questions/3359717/cannot-display-an-image-in-tkinter) – Nae Nov 25 '17 at 19:36

3 Answers3

14

tkinter has a PhotoImage class which can be used to display GIF images. If you want other formats (other than the rather outdated PGM/PPM formats) you'll need to use something like PIL or Pillow.

import Tkinter as tk

root = tk.Tk()
image = tk.PhotoImage(file="myfile.gif")
label = tk.Label(image=image)
label.pack()
root.mainloop()

It's important to note that if you move this code into a function, you may have problems. The above code works because it runs in the global scope. With a function the image object may get garbage-collected when the function exits, which will cause the label to appear blank.

There's an easy workaround (save a persistent reference to the image object), but the point of the above code is to show the simplest code possible.

For more information see this web page: Why do my Tkinter images not appear?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Thank you this is great, problem was my college wont let extra python modules such as PIL or Pillow to be installed on the system. :) – LuGibs Jan 26 '16 at 22:08
  • Sorry, when I tried it in my program it only shows a blank square where I would expect to see the image, so it must open the image as the dimensions are correct but it isn't displaying what is in the image? – LuGibs Jan 27 '16 at 11:44
  • 2
    Found the adding a line, label.image = image, made the image appear as it kept a reference. This works with .png files too. – LuGibs Jan 27 '16 at 11:50
  • The links are not functional. Kindly update. – Zia Feb 03 '21 at 05:31
  • @Zia: thanks for alerting me. I've fixed the links. – Bryan Oakley Feb 03 '21 at 15:36
0

You can use PIL library which available for python 3. First, you need to install PIL using this command (using pip): pip install pillow then:

`from tkinter import *`

from PIL import Image, ImageTk

`class Window(Frame):`

    `def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.pack(fill=BOTH, expand=1)
        load = Image.open("parrot.jpg")
        render = ImageTk.PhotoImage(load)
        img = Label(self, image=render)
        img.image = render
        img.place(x=0, y=0)`
-2

Luke, this is too late , however may help others. Your image has to be in the same sub directory with .py script. You can also type './imageFileName.png'