在python 3上使用tkinter打开图像

在python 3上使用tkinter打开图像,python,image,python-3.x,tkinter,Python,Image,Python 3.x,Tkinter,我在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) 当我运行它时,我只得到以下错误: Traceback (most recent call last): File

我在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)
当我运行它时,我只得到以下错误:

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
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site packages\spyderlib\widgets\externalshell\sitecustomize.py”,第685行,在runfile中
execfile(文件名、命名空间)
文件“C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site packages\spyderlib\widgets\externalshell\sitecustomize.py”,第85行,在execfile中
exec(编译(打开(文件名'rb').read(),文件名'exec'),命名空间)
文件“C:/Comp Sci/USB\u Virus/trollface\u puzzle\u picture.py”,第12行,在
photo=ImageTk.PhotoImage(图像)
文件“C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site packages\PIL\ImageTk.py”,第112行,在u_init中__
自拍照=tkinter.PhotoImage(**kw)
文件“C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\tkinter\\uuuuuu init\uuuu.py”,第3416行,在\uuu init中__
图像。_u初始(自我,“照片”,名称,cnf,主机,**千瓦)
文件“C:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\tkinter\\uuuuuu init\uuuu.py”,第3357行,在\uuu init中__
raise RUNTIMERROR('创建映像太早')
RuntimeError:创建映像太早

我做错了什么?

首先需要创建
Tk
的实例:

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()