温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何解决Python3.8+Tkinter: Button设置image属性不显示的问题

发布时间:2021-08-09 13:46:03 来源:亿速云 阅读:122 作者:小新 栏目:开发技术

这篇文章主要介绍了如何解决Python3.8+Tkinter: Button设置image属性不显示的问题,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。

        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)

如何解决Python3.8+Tkinter: Button设置image属性不显示的问题

        结果删除按钮不显示image,按钮上显示空白:

如何解决Python3.8+Tkinter: Button设置image属性不显示的问题

del_button的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)

如何解决Python3.8+Tkinter: Button设置image属性不显示的问题

        结果删除按钮的image显示正常:

如何解决Python3.8+Tkinter: Button设置image属性不显示的问题

del_button的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属性不显示的问题”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI