如何在文本小部件中嵌入图像 [英] how to embed an image in a text widget

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

问题描述

我知道可以在 Tkinter 文本小部件中嵌入图像,但我一直找不到一些简单的示例代码.具体来说,我需要嵌入一个 jpg,所以根据文档我认为我需要使用 photoimage 类

I know it is possible to embed an image in a Tkinter text widget, but I've been unable to find some simple example code. Specifically, I need to embed a jpg, so according to the docs I think I need to use the photoimage class

我尝试使用这个:

  img=PhotoImage ( file=imgfn )
  text.image_create(image=img)

其中 imgfn 是图像文件名,文本是我的文本小部件,但我得到_tkinter.TclError:无法识别图像文件中的数据......"

where imgfn is the image filename, and text is my text widget, but I get "_tkinter.TclError: couldn't recognize data in image file ..."

感谢您的帮助!

推荐答案

PhotoImage 只处理 GIFPGM/PPM 文件.为了在 Tkinter 中使用 JPEG,您可以使用 Python 成像库 (PIL) 创建一个 PhotoImage.

PhotoImage only handles GIF and PGM/PPM files. In order to use JPEG with Tkinter, you can use the Python Imaging Library (PIL) to create a PhotoImage.

from PIL import Image, ImageTk

img = Image.open("yourimg.jpg")
photoImg = ImageTk.PhotoImage(img)

或者,如果可能,您也可以使用 PhotoImage 的其他支持格式之一.

Alternatively you could just one of the other supported formats for PhotoImage if possible.

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

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