Question

I want to display the images in the folder using grid(). But when I tried with the following code, I got the output with single image iterated.

My code:

def messageWindow():
    win = Toplevel()
    path = 'C:\Users\HP\Desktop\dataset'
    for r in range(7):
        for c in range(10):
            for infile in glob.glob(os.path.join(path,'*.jpg')):
              im = Image.open(infile)
              resized = im.resize((100, 100),Image.ANTIALIAS)
              tkimage = ImageTk.PhotoImage(resized)
              myvar=Label(win,image = tkimage)
              myvar.image = tkimage
              myvar.grid(row=r,column=c)   
root = Tk()
button = Button(app, text='Images in DataSet',command = messageWindow)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 850, y = 60)
root.mainloop()  

When I run this code, after 5 minutes a child window will popup, and it will display a single image like this;

enter image description here

But how to get all the images in the dataset? Any suggestions are welcome. Tkanks for your support!

Was it helpful?

Solution

As I said in a comment, you're putting the same image in every row and column of the grid. Here's how to avoid that using the built-in divmod() function to iteratively compute the row and column for each one, based on the number of COLUMNS you want to display in each row based on the current value of image_count:

def messageWindow():
    win = Toplevel()
    path = r'C:\Users\HP\Desktop\dataset'
    COLUMNS = 10
    image_count = 0
    for infile in glob.glob(os.path.join(path, '*.jpg')):
        image_count += 1
        r, c = divmod(image_count-1, COLUMNS)
        im = Image.open(infile)
        resized = im.resize((100, 100), Image.ANTIALIAS)
        tkimage = ImageTk.PhotoImage(resized)
        myvar = Label(win, image=tkimage)
        myvar.image = tkimage
        myvar.grid(row=r, column=c)
    win.mainloop()  # Not sure if you need this, too, or not...

OTHER TIPS

You always use the same column and row for all images in the dataset.

Try removing the row and the column for-loop. and do something like this:

      c = 0
      r = 0  
      for infile in glob.glob(os.path.join(path,'*.jpg')):
          im = Image.open(infile)
          resized = im.resize((100, 100),Image.ANTIALIAS)
          tkimage = ImageTk.PhotoImage(resized)
          myvar=Label(win,image = tkimage)
          myvar.image = tkimage
          myvar.grid(row=r,column=c)   
          r += 1

This should be 70 times faster :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top