天天看點

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