国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

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

瀏覽:80日期:2022-07-28 13:19:57

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

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

”的錯誤。代碼1是導致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)

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

結果刪除按鈕不顯示image,按鈕上顯示空白:

Python3.8 + Tkinter: Button設置image屬性不顯示的問題及解決方法 del_button的image不顯示

嘗試將del_button的image指向的變量設置為局部變量,即下面所展示的代碼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)

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

結果刪除按鈕的image顯示正常:

Python3.8 + Tkinter: Button設置image屬性不顯示的問題及解決方法 del_button的image顯示正常

筆記:

不明所以的bug。判斷潛在原因是:GC的問題。image屬性需要指向明確的內存地址。方法返回的臨時變量地址調用后即被回收,導致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))

到此這篇關于Python3.8 + Tkinter: Button設置image屬性不顯示的問題的文章就介紹到這了,更多相關Python Tkinter按鈕不顯示內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 义马市| 毕节市| 城步| 南安市| 樟树市| 密山市| 东明县| 和田县| 怀安县| 定日县| 海兴县| 宁安市| 成安县| 顺平县| 南陵县| 锡林浩特市| 唐海县| 栾城县| 贵阳市| 平武县| 涿州市| 赤壁市| 酒泉市| 慈溪市| 桐柏县| 柯坪县| 莎车县| 巍山| 高邑县| 新闻| 故城县| 元阳县| 湾仔区| 芜湖县| 娱乐| 巴中市| 汝阳县| 盐池县| 筠连县| 北宁市| 博爱县|