How to display images in grid from a loop in tkinter

你。 提交于 2021-01-07 01:38:55

问题


i want to display images in row and columns...row should be of 4...the number of images will be random..

import tkinter as tk
from PIL import Image, ImageTk
from urllib.request import urlopen
from io import BytesIO

root = tk.Tk()

#number of urls will be random
URL_list = ["urls","urls","urls"]


for url in URL_list:

    u = urlopen(url)
    raw_data = u.read()
    u.close()

    im = Image.open(BytesIO(raw_data))
    photo = ImageTk.PhotoImage(im)

    label = tk.Label(image=photo)
    label.image = photo
    label.pack()

root.mainloop()


回答1:


The Grid geometry manager puts the widgets in a 2-dimensional table. The master widget is split into a number of rows and columns, and each “cell” in the resulting table can hold a widget. You can read more about it here.

To limit number of rows used, you can simply keep track of where you place your images.

import tkinter as tk
from PIL import Image, ImageTk
from urllib.request import urlopen
from io import BytesIO

root = tk.Tk()

#number of urls will be random
URL_list = ["urls","urls","urls"]

MAX_ROWS = 4
current_row = 0
current_column = 0

for url in URL_list:

    u = urlopen(url)
    raw_data = u.read()
    u.close()

    im = Image.open(BytesIO(raw_data))
    photo = ImageTk.PhotoImage(im)

    label = tk.Label(image=photo)
    label.image = photo
    label.grid(row = current_row, column = current_column)
    current_row += 1
    if (current_row >= 4):
        current_column += 1
        current_row = 0

root.mainloop()

This will place your images in following order:

1 5 9
2 6 10
3 7 ...
4 8 


来源:https://stackoverflow.com/questions/56307270/how-to-display-images-in-grid-from-a-loop-in-tkinter

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