python基础教程:python 实现在tkinter中动态显示label图片的方法

今天小编就为大家分享一篇python 实现在tkinter中动态显示label图片的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
在编程中我们往往会希望能够实现这样的操作:点击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并没有如我们所期望的那样变化。
r-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做出了详尽的解释。
原文如下:
Why do my Tkinter images not appear?
When you add a PhotoImage or other Image object to a Tkinter widget, you must keep your own reference to the image object. If you don’t, the image won’t always show up.

The problem is that the Tkinter/Tk interface doesn’t handle references to Image objects properly; the Tk widget will hold a reference to the internal object, but Tkinter does not. When Python’s garbage collector discards the Tkinter object, Tkinter tells Tk to release the image. But since the image is in use by a widget, Tk doesn’t destroy it. Not completely. It just blanks the image, making it completely transparent…

The solution is to make sure to keep a reference to the Tkinter object, for example by attaching it to a widget attribute:

photo = PhotoImage(…)

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
CATEGORY: gui

CATEGORY: tkinter
写到这里,给大家推荐一个资源很全的python学习聚集地,点击进入,这里有资深程序员分享以前学习

心得,学习笔记,还有一线企业的工作经验,且给大家精心整理一份python零基础到项目实战的资料,

每天给大家讲解python最新的技术,前景,学习需要留言的小细节
以上这篇python 实现在tkinter中动态显示label图片的方法就是小编分享给大家的全部内容了

发布了41 篇原创文章 · 获赞 34 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/haoxun08/article/details/104869200
今日推荐