bug如題目所描述。嘗試過(guò)將按鈕的image指向的變量del_icon設(shè)置為global全局變量,但是不成功,會(huì)提示如“
attributeerror: 'photoimage' object has no attribute '_photoimage__photo'
”的錯(cuò)誤。代碼1是導(dǎo)致bug的源頭。
代碼1:
1
2
3
4
5
6
7
8
|
#!/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:
1
2
3
4
5
6
7
8
9
|
#!/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的問(wèn)題。image屬性需要指向明確的內(nèi)存地址。方法返回的臨時(shí)變量地址調(diào)用后即被回收,導(dǎo)致image指向空地址。
resize()的代碼:
1
2
3
4
5
6
7
8
9
|
#!/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屬性不顯示的問(wèn)題的文章就介紹到這了,更多相關(guān)python tkinter按鈕不顯示內(nèi)容請(qǐng)搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_21264377/article/details/119523050