【问题标题】:Adding an image to text widget of Tkinter in python 2.7在 python 2.7 中将图像添加到 Tkinter 的文本小部件
【发布时间】:2016-02-21 09:52:17
【问题描述】:

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

【问题讨论】:

  • 文本小部件显然不支持图像。我最近需要文本小部件中的图片。我使用了一个画布,在上面放了一个框架,并将较小的框架打包为“线条”,在这些框架中我添加了带有文本和图像的标签。您可以找到所有操作方法。在画布上搜索可滚动的小部件,在标签上搜索图像并将其实现到您的代码中。
  • @Vivekkumarpathak 我认为人们在这里匆忙投反对票。 Tkinter Text 小部件确实支持嵌入图像。
  • @JozefMéry:你错了。文本小部件确实 支持嵌入图像。这是一个有据可查的功能,从一开始就在 tkinter 中。

标签: python tkinter python-imaging-library


【解决方案1】:

你只犯了两个小错误。当您将open 图像设置为image1 时,您使用的是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()

【讨论】:

  • 非常感谢它真的很有帮助:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多