我是 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()
请您参考如下方法:
你只犯了两个小错误。当您以 image1open 图像时,您使用的是 Python 的内置 open 关键字而不是 Image.open, PIL 的 Image 类的方法。当您打算引用 PIL 的 ImageTk.PhotoImage 类时,您还引用了 Tkinter 的 PhotoImage 类。这是您的固定代码:
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()
