在python 2.7中将图像添加到Tkinter的文本小部件 [英] Adding an image to text widget of Tkinter in python 2.7

查看:60
本文介绍了在python 2.7中将图像添加到Tkinter的文本小部件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Tkinter and i am trying to add an image to a text widget in Tkinter python 2.7 I have looked up some resources on the internet and as far as i have gotten is this code but it is giving error - "

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) 

"

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

please tell me where i went wrong. Thanks in advance :)

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类的方法.当您打算引用 PIL 的 ImageTk.PhotoImage 类时,您也引用了 Tkinter 的 PhotoImage 类.这是您的固定代码:

You have made just two small mistakes. When you open the image as image1 you are using Python's built-in open keyword rather than Image.open, the method of PIL's Image class. You also reference Tkinter's PhotoImage class when you mean to reference PIL's ImageTk.PhotoImage class. Here is your fixed code:

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

这篇关于在python 2.7中将图像添加到Tkinter的文本小部件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆