1

It seems like with one image - I can create 36 pictures, but for some reason, I cannot create 36 different images and display them on Canvas. Only one random image is shown in position 30, for the reason I do not quite get :)

There will be an image added. It seems like generating a random image in the for loop does not work. I have tried to move it around - does not help.

Here is what I get

from tkinter import *
import math
import random
time_to_remember = 60

suit = ["clubs","diamonds","spades","hearts"]
names_cards = ["6","7","8","9","10","jack","ace","king"]


def countdown(count):
    count_min = math.floor(count / 60)
    count_sec = math.floor(count % 60)
    if count_sec < 10:
        count_sec = f"0{math.floor(count % 60)}"
    timer_text.config( text=f"{count_min}:{count_sec}")

    if count < 10:
        timer_text.config( fg ="red")
    if count > 0:
        global timer
        timer = window.after(1000, countdown, count - 1)
    print(count)

window = Tk()
window.minsize(1000, 800)
canvas = Canvas(height=1000, width = 1000)
canvas.grid(row = 1, rowspan=6, column=0,columnspan=10 )

b_img = PhotoImage(file= "/Users/oleksandrzozulia/PycharmProjects/memory_project/Images/Screenshot 2022-08-27 at 11.48.49.png",
                   height=130,
                   width=80)
y_cor = 20
x_cor = 90
leng = 10
count = 0
ii = []
for i in range(0,4):
    if count == 3:
        leng = 6
    for i in range(0,leng):
        i = canvas.create_image(x_cor,y_cor, image=b_img, anchor="ne")
        x_cor += 100
    count +=1
    x_cor = 90
    y_cor += 150

#Display Random cards==================================================================

y_n = 20
x_n = 90
leng_n = 10
count_n = 0
for i in range(0,3):
    if count_n == 3:
        leng_n = 6
    for i in range(0,leng_n):
        img_n = PhotoImage(
            file = f"Images/PNG-cards-1.3/{random.choice(names_cards)}_of_{random.choice(suit)}.png",
            height=130,
            width = 80)
        i = canvas.create_image(x_n,y_n, image=img_n, anchor="ne")
        x_n += 100
    count +=1
    x_n = 90
    y_n += 150
  • This is a well known issue in tkinter. You need to keep references to the images, otherwise they become garbage. You could store them in a list for example. – Thingamabobs Aug 28 '22 at 09:14
  • Does this answer your question? [Why does Tkinter image not show up if created in a function?](https://stackoverflow.com/questions/16424091/why-does-tkinter-image-not-show-up-if-created-in-a-function) – Thingamabobs Aug 28 '22 at 09:14
  • It is because you used same variable to store the image references in the second for loop, so only the last one in the for loop will be shown. Also there are only 32 combinations of cards, but you created 36 cards in first for loop and 30 cards in second for loop. – acw1668 Aug 29 '22 at 01:50

0 Answers0