在 python 2.7 中将图像添加到 Tkinter 的文本小部件

Adding an image to text widget of Tkinter in python 2.7

我是 Tkinter 的新手,我正在尝试将图像添加到 Tkinter 中的文本小部件 python 2.7 我在互联网上查找了一些资源,据我所知是这段代码,但它给出了错误 - "

File "anim.py", line 11, in <module>
    text.image_create(END,image=photoImg)
  File "C:\Python27\lib\lib-tk\Tkinter.py", line 2976, in image_create
    *self._options(cnf, kw))
  TypeError: __str__ returned non-string (type file) 

请告诉我哪里出错了。提前致谢:)

from PIL import Image,ImageTk
from Tkinter import *
root = Tk()
root.geometry("900x900+100+100")
image1 = open('IMG_20160123_170503.jpg')
photoImg = PhotoImage(image1)
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
text.image_create(END,image=photoImg)
root.mainloop()

你只犯了两个小错误。当您 open 将图像设置为 image1 时,您使用的是 Python 的内置 open 关键字而不是 Image.open,PIL 的方法 Image class。当您要引用 PIL 的 ImageTk.PhotoImage class 时,您还引用了 Tkinter 的 PhotoImage class。这是您的固定代码:

from Tkinter import *
from PIL import Image,ImageTk
root = Tk()
root.geometry("900x900+100+100")
image1 = Image.open("IMG_20160123_170503.jpg")
photoImg = ImageTk.PhotoImage(image1)
frame = Frame(root)
frame.pack()
text = Text(frame)
text.pack()
text.image_create(END,image=photoImg)
root.mainloop()