It’s a Python beginner question.
I want to loop through several subfolders of parent folder (subfolders contain jpg and txt files). I want to show images using Tkinter. There should be an image and Next button beside – when button is clicked the next image from the list should be loaded.
How to force an application to stop on each image and wait for user reaction?
In the test code below the image loaded is from the last directory in the loop (images from other directories are not displayed although I can print their names during the loop run).
import Tkinter, os, glob
from PIL import Image, ImageTk
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.initialize()
def initialize(self):
self.grid
parentSrcFolder = r"D:\2012\RCIN\test"
srcFoldersLst = os.listdir(parentSrcFolder)
for srcFolder in srcFoldersLst:
jpgFilesPathLst = glob.glob(os.path.join(parentSrcFolder, srcFolder, "*.jpg"))
self.labelVariable = Tkinter.StringVar()
label = Tkinter.Label(self,textvariable=self.labelVariable,anchor="w")
label.grid(column=0,row=0,columnspan=2,sticky='EW')
self.labelVariable.set(jpgFilesPathLst[0])
cardImage = Image.open(jpgFilesPathLst[0])
indexCard = ImageTk.PhotoImage(cardImage)
labelImage = Tkinter.Label(self,image=indexCard)
labelImage.image = indexCard
labelImage.grid(column=0,row=3)
def main():
app = simpleapp_tk(None)
app.title('my application')
app.mainloop()
if __name__ == '__main__':
main()
The easiest way that I can think of doing this :
first, create a method
display_nextwhich 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 theIndexErrorthat 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: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 indisplay_nextjust update the widget usingconfig. Also, it’s probably better to inherit from Tkinter.Frame…EDIT
I’ve given an example of how to actually grid the Frame. In your previous example, you had
self.gridin your initialization code. This really did nothing. The only reason you had results was because you were inheriting fromTkinter.Tkwhich 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.