溫馨提示×

溫馨提示×

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

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

如何解決Python3.8+Tkinter: Button設置image屬性不顯示的問題

發(fā)布時間:2021-08-09 13:46:03 來源:億速云 閱讀:129 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要介紹了如何解決Python3.8+Tkinter: Button設置image屬性不顯示的問題,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

        Bug如題目所描述。嘗試過將按鈕的image指向的變量del_icon設置為global全局變量,但是不成功,會提示如“

AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'

”的錯誤。代碼1是導致bug的源頭。

        代碼1:

#!/bin/env python3
from PIL import ImageTk
import tkinter as tk
...
self.del_button = tk.Button(self.frame, text='DEL', width=20, height=20)
self.del_button.config(image=ImageTk.PhotoImage(resize(os.getcwd() + '/delete.png', 0)))
self.del_button.bind('<Button-1>', self.delete_selected_image)
self.del_button.grid(row=0, column=0, sticky=tk.W)

如何解決Python3.8+Tkinter: Button設置image屬性不顯示的問題

        結(jié)果刪除按鈕不顯示image,按鈕上顯示空白:

如何解決Python3.8+Tkinter: Button設置image屬性不顯示的問題

del_button的image不顯示

        嘗試將del_button的image指向的變量設置為局部變量,即下面所展示的代碼2。

        代碼2:

#!/bin/env python3
from PIL import ImageTk
import tkinter as tk
...
self.del_button = tk.Button(self.frame, text='DEL', width=20, height=20)
del_icon = ImageTk.PhotoImage(resize(os.getcwd()+'/delete.png', 0))
self.del_button.config(image=del_icon)
self.del_button.bind('<Button-1>', self.delete_selected_image)
self.del_button.grid(row=0, column=0, sticky=tk.W)

如何解決Python3.8+Tkinter: Button設置image屬性不顯示的問題

        結(jié)果刪除按鈕的image顯示正常:

如何解決Python3.8+Tkinter: Button設置image屬性不顯示的問題

del_button的image顯示正常

         筆記:

                不明所以的bug。判斷潛在原因是:GC的問題。image屬性需要指向明確的內(nèi)存地址。方法返回的臨時變量地址調(diào)用后即被回收,導致image指向空地址。


        resize()的代碼:

#!/bin/env python3
from PIL import Image
 
def resize(path):
    image = Image.open(path)
    raw_width, raw_height = image.size[0], image.size[1]
    min_height = 20
    min_width = int(raw_width * min_height / raw_height)
    return image.resize((min_width, min_height))

感謝你能夠認真閱讀完這篇文章,希望小編分享的“如何解決Python3.8+Tkinter: Button設置image屬性不顯示的問題”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!

向AI問一下細節(jié)

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

AI