image "pyimage4" doesn't exist

1.6k views Asked by At

I am new to Tkinter and this is the basic image displaying code that I found on the internet.

import tkinter as tk

from PIL import ImageTk, Image

path = r'.\0030001621.jpg'

root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

This is giving this error:

 ---------------------------------------------------------------------------
    TclError                                  Traceback (most recent call last)
    <ipython-input-10-ed688d6a5ab6> in <module>
          7 root = tk.Tk()
          8 img = ImageTk.PhotoImage(Image.open(path))
    ----> 9 panel = tk.Label(root, image = img)
         10 panel.pack(side = "bottom", fill = "both", expand = "yes")
         11 root.mainloop()

    c:\users\fatima.arshad\appdata\local\continuum\anaconda2\envs\web_scraping\lib\tkinter\__init__.py in __init__(self, master, cnf, **kw)
       2764 
       2765         """
    -> 2766         Widget.__init__(self, master, 'label', cnf, kw)
       2767 
       2768 class Listbox(Widget, XView, YView):

    c:\users\fatima.arshad\appdata\local\continuum\anaconda2\envs\web_scraping\lib\tkinter\__init__.py in __init__(self, master, widgetName, cnf, kw, extra)
       2297             del cnf[k]
       2298         self.tk.call(
    -> 2299             (widgetName, self._w) + extra + self._options(cnf))
       2300         for k, v in classes:
       2301             k.configure(self, v)

    TclError: image "pyimage4" doesn't exist

How do I solve this issue?

2

There are 2 answers

1
DaniyalAhmadSE On

Your code is 100% correct.

I think you haven't checked the "Add python to path" checkbox. while installing python. If that is the case try uninstalling Python and then reinstall python and don't forget to check the "Add python to path" checkbox this time.

0
Somraj Chowdhury On

Firstly make sure you have given the correct path for the image.

And then try the following method,

Try keeping a reference of the image to the Tkinter object.

import tkinter as tk
from PIL import ImageTk, Image

path = r'mposter.jpg'

root = tk.Tk()

img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)

# keep a reference
panel.image = img

panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

You can read about this in much more detail

http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm