_tkinter.TclError: couldn‘t recognize data in image file “E:\Python-Files\python-games\ch4\10.jp

编程入门 行业动态 更新时间:2024-10-19 07:29:18

问题描述:

Python使用Tkinter编写GUI,期望在其组件Label中显示图片(.png格式)报错:


实例代码:

from tkinter import *

win = Tk()      # 创建窗口对象
win.title("我的窗口")   # 设置窗口标题
lab1 = Label(win, text = '你好', anchor = 'nw') # 创建Label组件
lab1.pack()     # 显示Label组件

# 显示内置的位图
lab2 = Label(win, bitmap = 'question')  # 创建显示疑问图标的Label组件
lab2.pack()     # 显示Label组件

# 显示自选的图片
bm = PhotoImage(file = r'E:\Python-Files\python-games\ch4\10.jpg')
lab3 = Label(win, image = bm)
lab3.bm = bm
lab3.pack()     # 显示Label组件
win.mainloop()

原因分析:

Tkinter仅支持3种文件格式,即GIFPGMPPM


解决方案:

可以安装PIL模块,通过导入PIL模块,使用里面的函数实现。Python PIL支持GIFJPEG、PCD、PNG、PPM、PSD等30多种图像文件格式。

修改后的代码如下:

from tkinter import *
from PIL import Image, ImageTk

win = Tk()      # 创建窗口对象
win.title("我的窗口")   # 设置窗口标题
lab1 = Label(win, text = '你好', anchor = 'nw') # 创建Label组件
lab1.pack()     # 显示Label组件

# 显示内置的位图
lab2 = Label(win, bitmap = 'question')  # 创建显示疑问图标的Label组件
lab2.pack()     # 显示Label组件

# 显示自选的图片
bm = ImageTK.PhotoImage(file = r'E:\Python-Files\python-games\ch4\10.jpg')
lab3 = Label(win, image = bm)
lab3.bm = bm
lab3.pack()     # 显示Label组件
win.mainloop()

执行结果:


参考文章:

  • https://blog.csdn/liubing8609/article/details/78358923
  • https://blog.csdn/foneone/article/details/103063945

更多推荐

_tkinter.TclError: couldn‘t recognize data in image file “E:\Python-Files\pyth

本文发布于:2023-06-14 08:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1456637.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:data   image   file   _tkinter   TclError

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!