脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python3.8 + Tkinter: Button设置image属性不显示的问题及解决方法

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

2021-12-17 12:5198237982379 Python

这篇文章主要介绍了Python3.8 + Tkinter: Button设置image属性不显示的问题,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

        bug如题目所描述。尝试过将按钮的image指向的变量del_icon设置为global全局变量,但是不成功,会提示如“

attributeerror: 'photoimage' object has no attribute '_photoimage__photo'

”的错误。代码1是导致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)

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

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

 

 
Python3.8 + Tkinter: Button设置image属性不显示的问题及解决方法
del_button的image不显示

 

        尝试将del_button的image指向的变量设置为局部变量,即下面所展示的代码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)

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

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

 

 
Python3.8 + Tkinter: Button设置image属性不显示的问题及解决方法
del_button的image显示正常

 

         笔记:

                不明所以的bug。判断潜在原因是:gc的问题。image属性需要指向明确的内存地址。方法返回的临时变量地址调用后即被回收,导致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))

到此这篇关于python3.8 + tkinter: button设置image属性不显示的问题的文章就介绍到这了,更多相关python tkinter按钮不显示内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_21264377/article/details/119523050

延伸 · 阅读

精彩推荐