博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【BUG修复】:tkinter 使用 Label 显示 png、jpg 不能成功显示,但是不报错
阅读量:2091 次
发布时间:2019-04-29

本文共 1368 字,大约阅读时间需要 4 分钟。

问题描述:

tkinter 使用 Label 显示 png、jpg 不能成功显示,但是不报错。

所以问题应该出在图片的读取上。

源代码如下:

class Window:	……	def window():		……		self.imglabel = tk.Label(window, image=image)        self.imglabel.grid(row=4, column=1)		……    def show_lossImg():                img = Image.open("test.png")        image = ImageTk.PhotoImage(img)        self.imglabel.config(image=image)        #或者 self.imglabel["image"]=image

原因分析:

因为定义img 和 image的位置与主窗口定义位置不在一处(主窗口定义在主函数中,两个变量定义在子函数中),所以子函数执行结束,返回主函数时,两个变量作用域已经超出范围

解决方案:

1、在函数名下面加上global img, image即可

class Window:	……	def window():		……		self.imglabel = tk.Label(window, image=image)        self.imglabel.grid(row=4, column=1)		……    def show_lossImg():        	global img, image        img = Image.open("test.png")        image = ImageTk.PhotoImage(img)        self.imglabel.config(image=image)        #或者 self.imglabel["image"]=image

2、如果上述方法没有起作用,尝试为self.imglabel加背景颜色:self.imglabel.config(bg="red")。如果能正常显示背景颜色,说明图片已经正常显示,但是因为图片太大,所以和没有正常显示一样。

接下来只需要resize图片就可以了。如下:

class Window:	……	def window():		……		self.imglabel = tk.Label(window, image=image)        self.imglabel.grid(row=4, column=1)		……    def show_lossImg():        	global img, image        img = Image.open("test.png")        # resize 图片        image = ImageTk.PhotoImage(img.resize((50, 50)))        self.imglabel.config(image=image)        #为图片设置背景        self.imglabel.config(bg="red")

转载地址:http://opqqf.baihongyu.com/

你可能感兴趣的文章
笔试题(一)—— java基础
查看>>
Redis学习笔记(三)—— 使用redis客户端连接windows和linux下的redis并解决无法连接redis的问题
查看>>
Intellij IDEA使用(一)—— 安装Intellij IDEA(ideaIU-2017.2.3)并完成Intellij IDEA的简单配置
查看>>
Intellij IDEA使用(二)—— 在Intellij IDEA中配置JDK(SDK)
查看>>
Intellij IDEA使用(三)——在Intellij IDEA中配置Tomcat服务器
查看>>
Intellij IDEA使用(四)—— 使用Intellij IDEA创建静态的web(HTML)项目
查看>>
Intellij IDEA使用(五)—— Intellij IDEA在使用中的一些其他常用功能或常用配置收集
查看>>
Intellij IDEA使用(六)—— 使用Intellij IDEA创建Java项目并配置jar包
查看>>
Eclipse使用(十)—— 使用Eclipse创建简单的Maven Java项目
查看>>
Eclipse使用(十一)—— 使用Eclipse创建简单的Maven JavaWeb项目
查看>>
Intellij IDEA使用(十三)—— 在Intellij IDEA中配置Maven
查看>>
面试题 —— 关于main方法的十个面试题
查看>>
集成测试(一)—— 使用PHP页面请求Spring项目的Java接口数据
查看>>
FastDFS集群架构配置搭建(转载)
查看>>
目的:使用CUDA环境变量CUDA_VISIBLE_DEVICES来限定CUDA程序所能使用的GPU设备
查看>>
TP5.1模板布局中遇到的坑,配置完不生效解决办法
查看>>
TP5.1事务操作和TP5事务回滚操作多表
查看>>
TP5.1项目从windows的Apache服务迁移到linux的Nginx服务需要注意几点。
查看>>
win10安装软件 打开时报错 找不到 msvcp120.dll
查看>>
PHPunit+Xdebug代码覆盖率以及遇到的问题汇总
查看>>