Python3.8 + Tkinter: Button設(shè)置image屬性不顯示的問題及解決方法
Bug如題目所描述。嘗試過將按鈕的image指向的變量del_icon設(shè)置為global全局變量,但是不成功,會提示如“
AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
”的錯誤。代碼1是導(dǎo)致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)
結(jié)果刪除按鈕不顯示image,按鈕上顯示空白:
嘗試將del_button的image指向的變量設(shè)置為局部變量,即下面所展示的代碼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)
結(jié)果刪除按鈕的image顯示正常:
筆記:
不明所以的bug。判斷潛在原因是:GC的問題。image屬性需要指向明確的內(nèi)存地址。方法返回的臨時變量地址調(diào)用后即被回收,導(dǎ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))
到此這篇關(guān)于Python3.8 + Tkinter: Button設(shè)置image屬性不顯示的問題的文章就介紹到這了,更多相關(guān)Python Tkinter按鈕不顯示內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python數(shù)據(jù)合并的concat函數(shù)與merge函數(shù)詳解
大家都知道concat()函數(shù)可以沿著一條軸將多個對象進行堆疊,其使用方式類似數(shù)據(jù)庫中的數(shù)據(jù)表合并,在使用merge()函數(shù)進行合并時,默認會使用重疊的列索引做為合并鍵,即取行索引重疊的部分,本文給大家介紹python?數(shù)據(jù)合并concat函數(shù)與merge函數(shù),感興趣的朋友一起看看吧2022-05-05Python使用requirements.txt和pip打包批量安裝的實現(xiàn)
本文主要介紹了Python使用requirements.txt和pip打包批量安裝的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02Python 實現(xiàn)將大圖切片成小圖,將小圖組合成大圖的例子
這篇文章主要介紹了Python 實現(xiàn)將大圖切片成小圖,將小圖組合成大圖的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03Python遠程開發(fā)環(huán)境部署與調(diào)試過程圖解
這篇文章主要介紹了Python遠程開發(fā)環(huán)境部署與調(diào)試過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-12-12