Python Tkinter开发记忆游戏时after方法异常导致程序无限等待问题求助
问题原因分析
你遇到的无限等待/无响应问题是以下几个逻辑错误共同导致的:
- 异步执行顺序错误:
after()是Tkinter的异步调度方法,不会阻塞当前代码执行。你当前在sleep_secs()中调用screen.after(1000, reset)后立刻将no_press设为False,锁牌逻辑直接失效,没有等待1秒延迟结束就放开了点击限制。 - 计数触发逻辑错误:翻2张牌时
count就等于2,你当前判断count > 2才触发重置逻辑,需要用户点击第三张牌才会执行翻回动作,看起来就像程序卡住无响应。 - 状态变量未重置:
reset()函数只执行了翻回卡片的操作,没有清空已翻牌列表flipped、重置计数count,后续翻牌的状态完全混乱。 - 额外逻辑缺陷:你当前的
choose_images()实现无法保证每个公主图片恰好出现2次,会出现图片重复次数错误、可用图片不足的问题,且翻牌时的图片索引逻辑错误,会导致显示的图片和位置不匹配。
修正后可运行代码
from tkinter import * from random import shuffle 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") ] # 每个图片重复2次后打乱,保证恰好每组2张 chosen_images = images_list * 2 shuffle(chosen_images) buttons_list = [] flipped = [] card = PhotoImage(file="images/card.png") count = 0 no_press = False def replace_card(c, d): global flipped, count, no_press if no_press is True: return # 防止重复点击同一张牌 if buttons_list[c][d] in flipped: return count += 1 buttons_list[c][d].configure(image=chosen_images[c*8 + d]) flipped.append(buttons_list[c][d]) # 翻够2张就触发延迟判断 if count == 2: no_press = True # 判断两张牌是否相同 if flipped[0]['image'] == flipped[1]['image']: # 配对成功不用翻回,直接清空状态 flipped.clear() count = 0 no_press = False else: # 配对失败1秒后翻回 screen.after(1000, reset) def reset(): global card, no_press, count for element in flipped: element.configure(image=card) # 重置所有状态变量 flipped.clear() count = 0 no_press = False 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()
内容的提问来源于stack exchange,提问作者Roni
相关产品推荐
相关产品推荐

