2017-12-18 15 views
0

画像を持つクラスを作成したいのですが、マウスのクリックで次の画像に変更したいと思います。私は新しいのですが、私の考えはクラスを似ていました。新しい写真ごとに新しいクラスのインスタンスがある現実の生活に、このようにすることは可能でしょうか?ここに私のコードは画像をクリックするとピクチャが変わる画像のクラス

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.lab.destroy() Picture._count + = 1 self.img = Image.open(r'C:\ ImgArchive \ img%s.png '% Self.newImg = self.newImg'を返しますが、_tkinter.TclError:無効なコマンド名です。!ラベル "' I '私の新しいアイデアは、現実の生活に似たクラスを作ることでした。そこには、新しい絵が登場するたびに新しいクラスのインスタンスがありました。 –

答えて

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

ありがとう、これはうまく動作します。今私はパターンを参照してください:私は写真を変更するメソッドを使用できるようにラベルクラスから継承 –

関連する問題