广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python3.8 + Tkinter: Button设置image属性不显示的问题及解决方法
  • 251
分享到

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

PythonTkinter按钮不显示 2022-06-02 22:06:16 251人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

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

        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不显示
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)

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

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属性不显示的问题的文章就介绍到这了,更多相关Python Tkinter按钮不显示内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

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

本文链接: https://www.lsjlt.com/news/11166.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作