简单图片浏览器

本示例用于循环显示GIF图片,调用Python的标准库tkinter,如果要做更高端的图像处理应该采用PIL库。

import tkinter as tk,os  #导入库
class Application(tk.Frame):   #定义GUI的应用程序类,派生于Frmae
    def __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 += n
        if 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.img

root=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等错误。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值