Python3.8 + Tkinter: Button設(shè)置image屬性不顯示的問題及解決方法
Bug如題目所描述。嘗試過將按鈕的image指向的變量del_icon設(shè)置為global全局變量,但是不成功,會(huì)提示如“
AttributeError: ’PhotoImage’ object has no attribute ’_PhotoImage__photo’
”的錯(cuò)誤。代碼1是導(dǎo)致bug的源頭。
代碼1:
#!/bin/env python3from PIL import ImageTkimport 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不顯示
嘗試將del_button的image指向的變量設(shè)置為局部變量,即下面所展示的代碼2。
代碼2:
#!/bin/env python3from PIL import ImageTkimport 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顯示正常:
del_button的image顯示正常
筆記:
不明所以的bug。判斷潛在原因是:GC的問題。image屬性需要指向明確的內(nèi)存地址。方法返回的臨時(shí)變量地址調(diào)用后即被回收,導(dǎo)致image指向空地址。
resize()的代碼:
#!/bin/env python3from 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)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. XML入門的常見問題(四)2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. ASP動(dòng)態(tài)網(wǎng)頁(yè)制作技術(shù)經(jīng)驗(yàn)分享4. 解決ASP中http狀態(tài)跳轉(zhuǎn)返回錯(cuò)誤頁(yè)的問題5. ASP中if語(yǔ)句、select 、while循環(huán)的使用方法6. xml中的空格之完全解說7. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)8. ASP中解決“對(duì)象關(guān)閉時(shí),不允許操作。”的詭異問題……9. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法10. WMLScript的語(yǔ)法基礎(chǔ)
