本示例用于循环显示GIF图片,调用Python的标准库tkinter,如果要做更高端的图像处理应该采用PIL库。
import tkinter as tk,os #导入库
class Application(tk.Frame): #定义GUI的应用程序类,派生于Frmaedef __init__(self,master=None): #构造函数,master为父窗口self.files=os.listdir(r'f:\jpg') #获取图像文件名列表self.index=0 #图片索引,初始显示第一张self.img=tk.PhotoImage(file=r'f:\jpg'+'\\'+self.files[self.index])tk.Frame.__init__(self,master) #调用父类的构造函数self.pack() #调整显示的位置和大小self.createWidget() #类成员函数,创建子组件def createWidget(self):self.lblImage=tk.Label(self,width=300,height=300) #创建Label组件以显示图像self.lblImage['image']=self.img #显示第一张照片self.lblImage.pack() #调整显示位置和大小self.f=tk.Frame() #创建窗口框架self.f.pack()self.btnPrev=tk.Button(self.f,text="上一张",command=self.prev) #创建按钮self.btnPrev.pack(side=tk.LEFT)self.btnNext=tk.Button(self.f,text="下一张",command=self.next) #创建按钮self.btnNext.pack(side=tk.LEFT)def prev(self): #事件处理函数self.showfile(-1)def next(self): #事件处理函数self.showfile(1)def showfile(self,n):self.index += nif self.index<0:self.index=len(self.files)-1 #循环显示最后一张if self.index>len(self.files)-1:self.index=0 #循环显示第一张self.img=tk.PhotoImage(file=r'f:\jpg'+'\\'+self.files[self.index])self.lblImage['image']=self.imgroot=tk.Tk() #创建一个Tk根窗口组件
root.title("简单图片浏览器") #设置窗口标题
app=Application(master=root) #创建Application的对象实例
app.mainloop() #事件循环
运行结果:
注意,此处的PhotoImage只能处理.gif格式的图像,如果用PhotoImage打开JPG或者BMP格式会出现
_tkinter.TclError: couldn't recognize data in image file "f:\jpg\1.jpg等错误。