'My python tkinter buttons are updating too quickly after the wrong comparison is made

I'm trying to make a memory game for fun and as a learning experience, and I've run into the issue where even with something like time.sleep(.5) I still can't get buttons to update correctly with a delay. In fact the second button seems to update to hidden as it's about to show the proper image. I'm assuming the issue lies somewhere in the buttonClicked() function.

I'm trying to figure out how I can make it show one button, then the second, then wait half a second and hide both. And if someone understands why this is happening or where I could look into the issue and read up on my own, that would be helpful.

Thanks.

from re import A
import time
import tkinter as tk
from tkinter import *
from typing_extensions import Self
from PIL import Image, ImageTk
import glob
import os, os.path
import numpy as np
from sqlalchemy import null


#resize images and button
imgButtonWidth = 100
imgButtonHeight = 100
imgButtonSize = (imgButtonWidth,imgButtonHeight)
#Set the height and width of the game by number of items. 
width = 6
height = 6
#buttons = [[Button]*width]*height
#Total number of items 36 (0-35)
count = width*height-1
buttonList = []
#Will be a 2d array of [button, id]
answersList = []
clickedCount = 0
imgs = []
hiddenImg = null

# Create frame, set default size of frame and background color.
root = Tk()
root.title('Memory Game')
root.geometry(str(imgButtonWidth * (width+1)) + "x" + str(imgButtonHeight * (height+1)))
root.config(bg='darkblue')

frame = Frame(root, bg='darkblue')
# Fetch images from location and create a list of Image objects, then return.
def getImages():
    imgs = []
    path = "/home/paul/Programming/Python/MyMiniProjects/Mid/MemoryGame/"
    valid_images = [".jpg",".gif",".png",".tga"]
    
    for f in os.listdir(path):
        ext = os.path.splitext(f)[1]
        if ext.lower() not in valid_images:
            continue
        imgs.append([Image.open(os.path.join(path,f)).resize(imgButtonSize), f])
    return imgs + imgs

#Shuffle images for the game
imgs = getImages()
random.shuffle(imgs)

#Simple image to cover the tiles
hiddenImg = ImageTk.PhotoImage(Image.new('RGB', (imgButtonWidth, imgButtonHeight), (0,0,105)))

#Disable buttons after a match
def disable():
    global clickedCount, answersList

    clickedCount = 0
    for a in answersList:
        a[0]["state"] = "disabled"
        a[0]["bg"] = "green"
        answersList = []
#Hide buttons again
def hide():
    global clickedCount, answersList
      
    clickedCount = 0                      
    for a in answersList:                
        #a[0].config(image = hiddenImg)
        a[0]["image"] = hiddenImg       
        a[0]["state"] = "normal"    
        a[0]["bg"] = "white"    
        answersList = [] 
    
def wrong():
    for a in answersList:
        a[0]["bg"] = "red"
    
def buttonClicked(picture, id, button):
    global clickedCount, answersList
    
    print(clickedCount, len(answersList))
    #print(button.image, "1", hiddenImg, picture)    
    if button.image is hiddenImg and clickedCount < 2:          
        button["image"] = picture         
        button["state"] = "disabled"
        clickedCount += 1                    
        answersList.append([button, id])       

    if len(answersList) == 2:     
        
        #Check id but make sure it's not the same button pressed twice
        if answersList[0][1] is answersList[1][1]:#and answersList[0][0] is not answersList[1][0]:
            disable()
        else:       
            wrong()                 
            hide()
   

#Create the actual buttons with their respective image 
for h in range(height):    #print(buttons[w][::],"\n")    
    newList = []
    for w in range(width):        
        tempImage = imgs.pop(count)
        picture = ImageTk.PhotoImage(tempImage[0])
        id = tempImage[1]        
        button = Button(frame, image=hiddenImg,  state=NORMAL, height=imgButtonHeight, width=imgButtonWidth) 
        #Need to split this up because of how python handles closures
        button["command"] = lambda pic_temp=picture, id_temp=id, button_temp = button: buttonClicked(pic_temp, id_temp, button_temp)
        button.image = hiddenImg              
        #buttons[w][h].name = str(w + h)
        #buttons[w][h].grid(row=w, column=h, ipadx=random.randint(0,40), ipady=random.randint(0,40), padx=random.randint(0,5), pady=random.randint(0,5))
        button.grid(row=h, column=w, padx=1, pady=1)        
        #Button(frame, image=picture).grid(row=w, column=h, ipadx=random.randint(0,40), ipady=random.randint(0,40), padx=random.randint(0,5), pady=random.randint(0,5))
        count -= 1
       # buttonList.append(buttons[h][w])
        newList.append(button)
    buttonList.append(newList)

# for y in range(height):
#     for x in range(width):
#         print(ButtonList[y][x])
#     print("")


frame.pack(expand=True) 

root.mainloop()```



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source