How to loop through subfolders showing jpg in Tkinter? How to loop through subfolders showing jpg in Tkinter? tkinter tkinter

How to loop through subfolders showing jpg in Tkinter?


The easiest way that I can think of doing this :

first, create a method display_next which will increment an index and display the image associated with that index in a list (assume the list is a list of filenames). Enclosing the list inquiry in a try/except clause will let you catch the IndexError that happens when you run out of images to display -- At this point you can reset your index to -1 or whatever you want to happen at that point.

get the list of filenames in __init__ and initialize some index to -1 (e.g. self.index=-1).

create a tk.Button in __init__ like this:

self.Button = Tkinter.Button(self,text="Next",command=self.display_next)

Another side note, you can use a widget's config method to update a widget on the fly (instead of recreating it all the time). In other words, move all the widget creation into __init__ and then in display_next just update the widget using config. Also, it's probably better to inherit from Tkinter.Frame...

class SimpleAppTk(Tkinter.Frame):    def __init__(self,*args,**kwargs):        Tkinter.Frame.__init__(self,*args,**kwargs)        self.filelist=[]  #get your files here        #it probably would look like:        #for d in os.listdir(parentDir):        #    self.filelist.extend(glob.glob(os.path.join(parentDir,d,'*.jpg'))        self.index=-1        self.setup()        self.display_next()    def setup(self):        self.Label=Tkinter.Label(self)        self.Label.grid(row=0,column=0)        self.Button=Tkinter.Button(self,text="Next",command=self.display_next)        self.Button.grid(row=0,column=1)    def display_next(self):        self.index+=1        try:            f=self.filelist[self.index]        except IndexError:            self.index=-1  #go back to the beginning of the list.            self.display_next()            return        #create PhotoImage here        photoimage=...        self.Label.config(image=photoimage)        self.Label.image=photoimageif __name__ == "__main__":   root=Tkinter.Tk()   my_app=SimpleAppTk(root)   my_app.grid(row=0,column=0)   root.mainloop()

EDIT

I've given an example of how to actually grid the Frame. In your previous example, you had self.grid in your initialization code. This really did nothing. The only reason you had results was because you were inheriting from Tkinter.Tk which gets gridded automatically. Typically it's best practice to grid after you create the object because if you come back later and decide you want to put that widget someplace else in a different gui, it's trivial to do so. I've also changed the name of the class to use CamelCase in agreement with PEP 8 ... But you can change it back if you want.