Tkinter PhotoImage 踩坑记录

1.直接使用PhotoImage(file= ‘xxxx’)报错:_tkinter.TclError: couldn’t recognize data in image file “xxxxx.png”

原因:PhotoImage支持的图片格式有限。

解决办法:使用PILLOW库的ImageTk

1.如果没有安装PILLOW插件,请安装插件,使用 “pip install PILLOW”命令安装即可

2.生成PhotoImage对象:

代码:

from PIL import Image

from PIL import ImageTk

img = Image.open(filePath)

img = ImageTk.PhotoImage(img)

2.PhotoImage显示问题:显示空白框,大小是图片的真实大小

原因:见https://docs.Python.org/2/library/tkinter.html#images,说白了就是图像数据引用被回收了图片就显示不出来了,只会显示一个空box。

解决办法:保存PhotoImage对象即可,示例代码如下:

代码:

imgDict = {}
def getImgWidget(filePath):

    if os.path.exists(filePath) and os.path.isfile(filePath):

        if filePath in imgDict and imgDict[filePath]:

            return imgDict[filePath]

        img = Image.open(filePath)

        #print(img.size)

        img = ImageTk.PhotoImage(img)

        imgDict[filePath] = img

        return img

    return None

你可能感兴趣的:(Python)