一:背景
由于标签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()
四:原因分析
根本原因目前还不清楚,如果有哪位朋友知道的可以给我留言,谢谢!