Tk 标签Label下image参数直接调用包含 ImageTk.PhotoImage 的函数时,图片不显示问题

一:背景

    由于标签Label中image参数无法直接使用非gif的图片,所以使用PIL(Python Image Library)库实现非gif图片的使用。

二:修改前的代码

#coding=utf-8

from Tkinter import *
from PIL import Image,ImageTk

class Interface():
    
    def __init__(self):
        self.win = Tk()
        self.win.title('界面')  # 标题
        label = Label(self.win,
                       image=self.Jpg2gif('reboot.jpg'))
        label.pack()
        self.win.mainloop()

    def Jpg2gif(self,image_path):
        image = Image.open(image_path)
        image =  ImageTk.PhotoImage(image)
        print image,type(image)    #pyimage1 <class 'PIL.ImageTk.PhotoImage'>
        return image
        
if __name__ == '__main__':
    Interface()

三:解决方法

方法1:在label 外调用函数 Jpg2gif()

#coding=utf-8

from Tkinter import *
from PIL import Image,ImageTk

class Interface():
    
    def __init__(self):
        self.win = Tk()
        self.win.title('界面')  # 标题
        image_jpg = self.Jpg2gif('reboot.jpg') #先调用函数,再将image_jpg传入label中image参数
        label = Label(self.win,
                       image=image_jpg )
        label.pack()
        self.win.mainloop()

    def Jpg2gif(self,image_path):
        image = Image.open(image_path)
        image =  ImageTk.PhotoImage(image)
        print image,type(image)    #pyimage1 <class 'PIL.ImageTk.PhotoImage'>
        return image
        
if __name__ == '__main__':
    Interface()

方法2:加入全局变量声明

#coding=utf-8

from Tkinter import *
from PIL import Image,ImageTk

class Interface():
    
    def __init__(self):
        self.win = Tk()
        self.win.title('界面')  # 标题
        label = Label(self.win,
                       image=self.Jpg2gif('reboot.jpg'))
        label.pack()
        self.win.mainloop()

    def Jpg2gif(self,image_path):
        global image    #声明image为全局变量
        image = Image.open(image_path)
        image =  ImageTk.PhotoImage(image)
        print image,type(image)    #pyimage1 <class 'PIL.ImageTk.PhotoImage'>
        return image
        
if __name__ == '__main__':
    Interface()

方法3:将image参数实例化

#coding=utf-8

from Tkinter import *
from PIL import Image,ImageTk

class Interface():
    
    def __init__(self):
        self.win = Tk()
        self.win.title('界面')  # 标题
        label = Label(self.win,
                       image=self.Jpg2gif('reboot.jpg'))
        label.pack()
        self.win.mainloop()

    def Jpg2gif(self,image_path):
        image = Image.open(image_path)
        self.image =  ImageTk.PhotoImage(image)    #将image改成实例化参数 self.image
        print self.image,type(self.image)    #pyimage1 <class 'PIL.ImageTk.PhotoImage'>
        return self.image
        
if __name__ == '__main__':
    Interface()

四:原因分析

    根本原因目前还不清楚,如果有哪位朋友知道的可以给我留言,谢谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值