python 實現(xiàn)在tkinter中動態(tài)顯示label圖片的方法
在編程中我們往往會希望能夠實現(xiàn)這樣的操作:點擊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)
但這個時候會發(fā)現(xiàn)Label并沒有如我們所期望的那樣變化。
這時候我去網(wǎng)上查找了相關資料,在 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!
于是在他的啟發(fā)下我將代碼進行了修改,之后完美解決了問題。修改后函數(shù)部分的代碼如下:
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
而由于本人才疏學淺,對于造成這種現(xiàn)象的原因尚不理解。不過那名外國回答者也給出了這樣修改的原因,在 http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm 上對于為何要keep a reference做出了詳盡的解釋。
原文如下:

以上這篇python 實現(xiàn)在tkinter中動態(tài)顯示label圖片的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Python 中使用 PyMySQL模塊操作數(shù)據(jù)庫的方法
這篇文章主要介紹了Python 中使用 PyMySQL模塊操作數(shù)據(jù)庫的方法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-11-11

