Reputation: 37
import tkinter as tk
from PIL import Image,ImageTk
import random
win = tk.Tk()
win.title('Country game')
win.geometry('2800x2800')
countries = ['Australia.png','Brazil.png','China.png','Egypt.png','France.png','Germany.png',
'Italy.png','Spain.png','UK.png']
random.shuffle(countries)
for country in countries:
img = Image.open(country)
landmark = ImageTk.PhotoImage(img)
btn = tk.Button(win,image=landmark)
btn.image = landmark
for i in range(3):
for j in range(3):
btn.grid(row=i,column=j)
For this program, it does not show any error messages. However my aim is to place the nine images randomly on the tkinter window, but when I run this program only one image button did appear. Although I used two for loops to grid other eight ones do not appear. May I ask what is the best method to place nine images for 3 rows and 3 images per row?
Upvotes: 0
Views: 270
Reputation: 386285
You are looping over nine images, and for each of those nine images you are calling grid
nine times, for a total of 81 calls to grid
. And, since only the last call to grid for any single button is the only one that has an effect, all nine buttons are ultimately ending up at row 2, column 2. That is why you see a single button. They are all there, but they are all at the same location.
You don't need to iterate over the list of countries and the rows and columns. Instead, just iterate over the rows and columns and pull the next image from the randomized list of images:
random.shuffle(countries)
for row in range(3):
for column in range(3):
image_file = countries.pop()
img = Image.open(image_file)
landmark = ImageTk.PhotoImage(img)
btn = tk.Button(win,image=landmark)
btn.image = landmark
btn.grid(row=row, column=column)
Upvotes: 4