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)
结果删除按钮不显示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)
结果删除按钮的image显示正常:
笔记:
不明所以的bug。判断潜在原因是:GC的问题。image属性需要指向明确的内存地址。方法返回的临时变量地址调用后即被回收,导致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属性不显示的问题的文章就介绍到这了,更多相关Python Tkinter按钮不显示内容请搜索华域联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持华域联盟!
您可能感兴趣的文章:
- python tkinter 获得按钮的文本值
- python基于tkinter点击按钮实现图片的切换
- 在python tkinter界面中添加按钮的实例
- Python tkinter布局与按钮间距设置方式
- Python的Tkinter点击按钮触发事件的例子
- Python 窗体(tkinter)按钮 位置实例
- python3 tkinter实现点击一个按钮跳出另一个窗口的方法
- python-tkinter之按钮的使用,开关方法
声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。





评论(0)