单击鼠标时更改图片的图片视图类 [英] Class for picture view that change pic on mouse click

查看:44
本文介绍了单击鼠标时更改图片的图片视图类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个有图片的类,并通过鼠标单击将其更改为下一个类.我是新手,我的想法是使类类似于现实生活,其中有新的类实例每张新照片,是否可以这样做?这是我的代码

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

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

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

代替这个

那为什么会发生?它的优雅方式是什么?

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

推荐答案

下面的示例生成一个简单的图像查看器,测试路径为C:\Users\Public\Pictures\Sample Pictures,请告诉我如果有什么不清楚的:

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

这篇关于单击鼠标时更改图片的图片视图类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆