问题
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