I'm making a memory game in Python Tkinter. After a card is flipped, I'm using the after method to make the reset function in my code delay for one second before the card is flipped back. It makes the function just wait forever. Can someone please explain why it's doing that? My code:
from tkinter import *
from random import choice
screen = Tk()
screen.title("Disney Princesses Memory Game")
width = screen.winfo_screenwidth()
height = screen.winfo_screenheight()
screen.geometry("%dx%d" % (width, height))
screen.configure(bg="#e0bce5")
title = Label(screen, text="Memory Game", font=("David", 50, "underline", "bold"), bg="#e0bce5")
title.place(x=400, y=20)
images_list = [
PhotoImage(file="images/aurora.png"),
PhotoImage(file="images/belle.png"),
PhotoImage(file="images/cinderella.png"),
PhotoImage(file="images/jasmine.png"),
PhotoImage(file="images/mulan.png"),
PhotoImage(file="images/rapunzel.png"),
PhotoImage(file="images/snow white.png"),
PhotoImage(file="images/tiana.png")
]
buttons_list = []
chosen_images = []
flipped = []
num_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
card = PhotoImage(file="images/card.png")
count = 0
no_press = False
def choose_images():
for num in range(16):
chosen_image = choice(images_list)
num_list[num] += 1
if num_list[num] > 2:
num += 1
continue
else:
chosen_images.append(chosen_image)
def replace_card(c, d):
global flipped, count, no_press
if no_press is True:
return
count += 1
if count > 2:
count = 0
no_press = True
sleep_secs()
else:
buttons_list[c][d].configure(image=chosen_images[d])
flipped.append(buttons_list[c][d])
def reset():
global card, no_press
for element in flipped:
element.configure(image=card)
def sleep_secs():
global no_press
screen.after(1000, reset)
no_press = False
choose_images()
x = 100
y = 250
for i in range(2):
buttons_list.append([])
for j in range(8):
a = Button(screen, image=card, command=lambda i=i, j=j: replace_card(i, j))
x += 100
a.place(x=x, y=y)
buttons_list[i].append(a)
y += 100
x = 100
screen.mainloop()
The weird thing about the after method for me is that it worked when I implemented it in a smaller program:
from tkinter import *
screen = Tk()
screen.geometry("600x800+30+10")
hi = Label(screen)
hi.place(x=20, y=20)
def reset():
hi.configure(text="hi", font=("Ariel", 30))
def sleep_secs():
screen.after(2000, reset)
print(2)
sleep_secs()
screen.mainloop()
What's the deal with that?