1

I made the following (and very short) code on Python 3:

from tkinter import *
from PIL import Image, ImageTk

image = Image.open("Trollface.jpg")
photo = ImageTk.PhotoImage(image)
canvas.create_image(0, 0, image = photo)

When I run it, I just get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
    execfile(filename, namespace)
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
    exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
  File "C:/Comp Sci/USB_Virus/trollface_puzzle_picture.py", line 12, in <module>
    photo = ImageTk.PhotoImage(image)
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\PIL\ImageTk.py", line 112, in __init__
    self.__photo = tkinter.PhotoImage(**kw)
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\tkinter\__init__.py", line 3416, in __init__
    Image.__init__(self, 'photo', name, cnf, master, **kw)
  File "C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\tkinter\__init__.py", line 3357, in __init__
    raise RuntimeError('Too early to create image')
RuntimeError: Too early to create image

What am I doing terribly wrong?

1 Answer 1

1

You need to create an instance of Tk first:

root = Tk()

from tkinter import *
from PIL import Image, ImageTk


root = Tk()

canvas = Canvas(width=500, height=500, bg='white')
canvas.pack()
image = Image.open("Trollface.jpg")
photo = ImageTk.PhotoImage(image)
canvas.create_image(250, 250, image=photo)

root.mainloop()

The code above essentially comes from here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.