天天看点

python _tkinter.TclError: couldn‘t recognize data in image file

python _tkinter.TclError: couldn‘t recognize data in image file

问题描述——tkinter.TclError: couldn‘t recognize data in image file

问题原因

出现该问题的原因是tkinter.PhotoImage()仅支持GIF and PGM/PPM 文件格式等几种不常用的图片格式问题

  如下:

bm=PhotoImage(file=r'D:\\a\\aa.jpg')      

如果想用 ".jpg"文件格式,直接用上面的代码,会报“couldn’t recognize data in image file "bm=PhotoImage(file=r’D:\a\aa.jpg’)"错误。

而且直接修改图片后缀为.gif格式也会出现这样的问题,修改方法只能从根本上修改如下(用ImageTK)

gif文件以及png文件可以借助PhotoImage()方法。这是Tkinter方法, 这意味着你无需导入任何其他模块即可使用。

photo = PhotoImage(file=r'【文件名】.gif')
label = Label(【Tk对象】, image=photo)      

代码示例:

from tkinter import *

root = Tk()

photo = PhotoImage(file="D:\\a\\aa.jpg"),
label = Label(root, image=photo)

label.pack()

root.mainloop()      

解决方法

如果要在标签内显示jpg需要借助PIL模块的Image和ImageTk模块,安装pillow模块

首先要安装pillow模块

pip install pillow      

其次要在程序中引入Image和ImageTk模块

from PIL import ImageTk, Image      

最后使用模块实现图片的导入

photo = ImageTk.PhotoImage(file=r'【文件名】.jpg')
label = Label(【Tk对象】, image=photo)      

示例2:

from tkinter import *
from PIL import Image, ImageTk

root = Tk()

photo = ImageTk.PhotoImage(file="19.jpg"),
label = Label(root, image=photo)

label.pack()

root.mainloop()      
python _tkinter.TclError: couldn‘t recognize data in image file