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

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

服务器之家 - 脚本之家 - Python - python 实现在tkinter中动态显示label图片的方法

python 实现在tkinter中动态显示label图片的方法

2021-07-11 01:01Cat7102 Python

今天小编就为大家分享一篇python 实现在tkinter中动态显示label图片的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

在编程中我们往往会希望能够实现这样的操作:点击button,选择了图片,然后在窗口中的label处显示选到的图片。那么这时候就需要如下代码:

python" id="highlighter_189882">
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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进行处理。这时候代码如下:

?
1
2
3
4
5
6
7
8
9
10
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 下看到了回答者给出的解决办法:

?
1
2
3
photo = imagetk.photoimage(self.img)
self.label1.configure(image = photo)
self.label1.image = photo # keep a reference!

于是在他的启发下我将代码进行了修改,之后完美解决了问题。修改后函数部分的代码如下:

?
1
2
3
4
5
6
7
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做出了详尽的解释。

原文如下:

python 实现在tkinter中动态显示label图片的方法

以上这篇python 实现在tkinter中动态显示label图片的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/Cat7102/article/details/79180312

延伸 · 阅读

精彩推荐