用于在鼠标点击时更改图片的图片视图的类

时间:2017-12-18 02:19:39

标签: python oop tkinter

我想创建一个有图片的课程,然后通过鼠标点击将其更改为下一个。我是oop的新手,我的想法是让课程类似于真实生活,其中有新的类实例每一张新照片,都可以这样做吗?这是我的代码

import tkinter as tk
from PIL import Image,ImageTk
class Picture():
    _count=1
    def __init__(self,window):
        self.id=Picture._count
        Picture._count+=1
        self.img=Image.open(r'C:\ImgArchive\img%s.png' % self.id)
        self.pimg = ImageTk.PhotoImage(self.img)
        self.lab=tk.Label(window,image=self.pimg)
        self.lab.pack()
        self.lab.bind('<1>',self.click)
    def click(self,event):
        self.lab.destroy()
        self=self.__init__(window)
window = tk.Tk()
window.title('Album')
window.geometry('1200x900')
pic=Picture(window)
window.mainloop()

它工作正常,但我不确定我的班级的旧实例是否被删除,是吗?我使用self.lab.destroy()因为如果我没有新图片出现,就像这样

#

而不是

#

那么为什么会这样?它的优雅方式是什么?

1 个答案:

答案 0 :(得分:0)

下面的示例生成一个使用C:\Users\Public\Pictures\Sample Pictures路径测试的简单图像查看器,让我知道是否有任何不清楚的地方:

import tkinter as tk
from PIL import Image, ImageTk
#required for getting files in a path
import os

class ImageViewer(tk.Label):
    def __init__(self, master, path):
        super().__init__(master)

        self.path = path
        self.image_index = 0

        self.list_image_files()
        self.show_image()

        self.bind('<Button-1>', self.show_next_image)

    def list_files(self):
        (_, _, filenames) = next(os.walk(self.path))
        return filenames

    def list_image_files(self):
        self.image_files = list()
        for a_file in self.list_files():
            if a_file.lower().endswith(('.jpg', '.png', '.jpeg')):
                self.image_files.append(a_file)

    def show_image(self):
        img = Image.open(self.path + "\\" + self.image_files[self.image_index])
        self.img = ImageTk.PhotoImage(img)
        self['image'] = self.img

    def show_next_image(self, *args):
        self.image_index = (self.image_index + 1) % len(self.image_files)
        self.show_image()

root = tk.Tk()

mypath = r"C:\Users\Public\Pictures\Sample Pictures"
a = ImageViewer(root, mypath)
a.pack()

root.mainloop()