python 实现在tkinter中动态显示label图片的方法
作者:Cat7102 时间:2022-07-17 11:10:15
在编程中我们往往会希望能够实现这样的操作:点击Button,选择了图片,然后在窗口中的Label处显示选到的图片。那么这时候就需要如下代码:
from tkinter import *
from tkinter.filedialog import askopenfilename
def choosepic():
path_=askopenfilename()
path.set(path_)
img_gif=Tkinter.PhotoImage(file='xxx.gif')
l1.config(image=img_gif)
root=Tk()
path=StringVar()
Button(root,text='选择图片',command=choosepic).pack()
e1=Entry(root,state='readonly',text=path)
e1.pack()
l1=Label(root)
l1.pack()
root.mainloop
而由于tkinter只能识别gif格式的图片,如果我们要添加jpg或者png格式的图片的话就要借用PIL进行处理。这时候代码如下:
from tkinter import *
from tkinter.filedialog import askopenfilename
from PIL import Image,ImageTk
def choosepic():
path_=askopenfilename()
path.set(path_)
img_open = Image.open(e1.get())
img=ImageTk.PhotoImage(img_open)
l1.config(image=img)
但这个时候会发现Label并没有如我们所期望的那样变化。
这时候我去网上查找了相关资料,在 https://stackoverflow.com/questions/14291434/how-to-update-image-in-tkinter-label 下看到了回答者给出的解决办法:
photo = ImageTk.PhotoImage(self.img)
self.label1.configure(image = photo)
self.label1.image = photo # keep a reference!
于是在他的启发下我将代码进行了修改,之后完美解决了问题。修改后函数部分的代码如下:
def choosepic():
path_=askopenfilename()
path.set(path_)
img_open = Image.open(e1.get())
img=ImageTk.PhotoImage(img_open)
l1.config(image=img)
l1.image=img #keep a reference
而由于本人才疏学浅,对于造成这种现象的原因尚不理解。不过那名外国回答者也给出了这样修改的原因,在 http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm 上对于为何要keep a reference做出了详尽的解释。
原文如下:
来源:https://blog.csdn.net/Cat7102/article/details/79180312
标签:python,tkinter,label
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
网站设计做好超级链接的重要性
2007-09-14 11:19:00
Python实现字典序列ChainMap
2022-07-01 21:34:56
![](https://img.aspxhome.com/file/2023/9/109479_0s.png)
Python正则表达式中的re.S的作用详解
2021-12-30 11:54:42
go build失败报方法undefined的解决过程
2023-06-18 15:07:36
![](https://img.aspxhome.com/file/2023/8/87628_0s.png)
Python基于yield遍历多个可迭代对象
2023-01-05 23:01:32
python 包实现JSON 轻量数据操作
2022-11-13 05:40:32
在Python中利用pickle保存变量的实例
2021-05-04 04:25:50
![](https://img.aspxhome.com/file/2023/2/68882_0s.jpg)
Python实现爬虫抓取与读写、追加到excel文件操作示例
2023-11-10 09:08:34
Python Flask 上传文件测试示例
2021-01-08 05:51:34
Python实现计算图像RGB均值方式
2024-01-01 20:50:31
![](https://img.aspxhome.com/file/2023/3/99513_0s.jpg)
python列表操作之extend和append的区别实例分析
2023-08-02 15:14:30
浅谈python字符串方法的简单使用
2021-07-14 11:16:25
rs.getrows的使用方法
2008-04-05 14:01:00
asp如何制作一个简单的翻页程序?
2010-06-29 21:26:00
详解python使用pip安装第三方库(工具包)速度慢、超时、失败的解决方案
2023-11-24 18:03:27
![](https://img.aspxhome.com/file/2023/0/65020_0s.jpg)
如何实现删除numpy.array中的行或列
2022-05-09 14:55:03
Python使用paramiko连接远程服务器执行Shell命令的实现
2023-01-19 15:25:39
JavaScript 日期联动选择器
2010-08-01 10:18:00
如何限制上传文件的大小?
2010-06-09 18:47:00
Python简单网络编程示例【客户端与服务端】
2023-12-07 10:26:55