2017-12-18 384 views
0

我想创建一个有图片的类,并通过鼠标点击更改为下一个类。我是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(),因为如果我不新图片显示了下来,像这样

#

,而不是这个

#

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

+0

命令'自我=自我.__的init __(...)'是代码的最不寻常的线 - 这意味着你必须更好地组织代码并将一些代码从'__init__'移动到分离的方法 - 然后运行这个方法insife'__init__'而不是'self = self .__ init __()' – furas

+0

更好地使用'self。 lab [“image”] = new_image'来替换现有标签中的图像。 – furas

+0

我试过这个'def click(self,event): self.lab.destroy() Picture._count + = 1 self.img = Image.open(r'C:\ ImgArchive \ img%s.png'%图片._count) self.newImg = ImageTk.PhotoImage(self.img) self.lab [“image”] = self.newImg',但得到错误'_tkinter.TclError:invalid command name“。!label”'I“对于OOP来说,我的想法是让类与现实生活类似,每个新图片都有新的类实例,是否可以做某种方式? –

回答

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

谢谢,这工作正常。现在我看到模式:从Label类继承,所以我可以使用方法来更改图片 –