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圖片的方法就是小編分享給大家的全部內容了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章