how to display different images using grid function using tkinter?

你离开我真会死。 提交于 2019-12-06 04:42:11

问题


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;

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


回答1:


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...



回答2:


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 :)



来源:https://stackoverflow.com/questions/22882249/how-to-display-different-images-using-grid-function-using-tkinter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!