图片浏览类改变鼠标点击图片
我想创建一个有图片的类,并通过鼠标点击更改为下一个类。我是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(),因为如果我不新图片显示了下来,像这样
,而不是这个
那么为什么会发生?什么是高雅它的方式?
回答:
下面的示例生成与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() 
以上是 图片浏览类改变鼠标点击图片 的全部内容, 来源链接: utcz.com/qa/260517.html


