Class for picture view that change pic on mouse cl

2019-08-27 16:58发布

I want to make a class that has a picture and it is changed to the next one by mouse click.I'm new to oop, my idea here was to make class similar to real life where there is new class instance for every new picture, is it possible to do it this way? Here is my code

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()

It works fine, but i'm not sure that old instances of my class is deleted, are they? And i use self.lab.destroy() because if i dont new picture appears down, like this

#

instead of this

#

So why it happens?What is elegant way for it?

1条回答
一纸荒年 Trace。
2楼-- · 2019-08-27 17:31

Below example produces a simple image viewer tested with path of C:\Users\Public\Pictures\Sample Pictures, let me know if anything's unclear:

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()
查看更多
登录 后发表回答