溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python的ImageTk.PhotoImage坑怎么解決

發(fā)布時間:2022-12-01 10:12:00 來源:億速云 閱讀:147 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“python的ImageTk.PhotoImage坑怎么解決”,在日常操作中,相信很多人在python的ImageTk.PhotoImage坑怎么解決問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”python的ImageTk.PhotoImage坑怎么解決”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

python的ImageTk.PhotoImage大坑

如果大家遇到這樣的報錯:

Exception in Tkinter callback
Traceback (most recent call last):
  File "E:\Anaconda3_files\lib\site-packages\PIL\Image.py", line 2515, in fromarray
    mode, rawmode = _fromarray_typemap[typekey]
KeyError: ((1, 1, 3), '<f8')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\Anaconda3_files\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "D:\Junior Spring\Digital Image Processing and Experiment\數(shù)字實驗備份\結課實驗\ImgProcessing.py", line 806, in Sobel_Sharpening
    image = ImageTk.PhotoImage(Image.fromarray(img))
  File "E:\Anaconda3_files\lib\site-packages\PIL\Image.py", line 2517, in fromarray
    raise TypeError("Cannot handle this data type")
TypeError: Cannot handle this data type

網(wǎng)上很多教程的方法我也試過,沒有用,也調(diào)試不出為什么

這里有個很關鍵的信息:Cannot handle this data type

說明是數(shù)據(jù)的類型錯了,但再三檢查后,明明就是帶入的<class &lsquo;numpy.ndarray&rsquo;>類型

所以,大坑來了

請仔細檢查自己array里面每個數(shù)的類型,它必須是<class &lsquo;numpy.uint8&rsquo;>,否則就會報錯

可以這樣改:

dst = dst.astype(np.uint8)
image = ImageTk.PhotoImage(Image.fromarray(dst))

Tkinter PhotoImage 踩坑記錄

1.直接使用PhotoImage(file= &lsquo;xxxx&rsquo;)報錯:_tkinter.TclError: couldn&rsquo;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顯示問題:顯示空白框,大小是圖片的真實大小

原因:說白了就是圖像數(shù)據(jù)引用被回收了圖片就顯示不出來了,只會顯示一個空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的ImageTk.PhotoImage坑怎么解決”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI