如何将PIL与Tkinter一起使用?

Yes*_*ke. 3 python tkinter python-imaging-library

在使用PIL加载图像并将其显示在由Tkinter创建的窗口中时,我在一个非常基本的层面上遗漏了一些东西.我想要做的最简单的形式是:

import Tkinter as TK
from PIL import Image, ImageTk

im = Image.open("C:\\tinycat.jpg")
tkIm = ImageTk.PhotoImage(im)
tkIm.pack()
TK.mainloop()
Run Code Online (Sandbox Code Playgroud)

当我尝试运行上面的代码时,我得到以下内容:

RuntimeError: Too early to create image
Exception AttributeError: "PhotoImage instance has no attribute 
'_PhotoImage__photo'" in <bound method PhotoImage.__del__ of 
<PIL.ImageTk.PhotoImage instance at 0x00C00030>> ignored
Run Code Online (Sandbox Code Playgroud)

我已经确认文件存在,可以在图像编辑器中打开,也可以使用im.show()显示.我错过了什么?

Mer*_*son 6

在调用ImageTk.PhotoImage()之前,必须先实例化Tkinter:

TK.Tk()
Run Code Online (Sandbox Code Playgroud)