Tkinter游戏关卡:切换新图片后计时器加速问题求助
解决Tkinter国旗猜谜游戏计时器加速问题
问题原因
每次切换国旗时,旧的计时器任务(通过new.after()创建的定时回调)没有被取消,导致多个计时任务同时在后台运行,叠加后就会出现倒计时速度越来越快的现象。
解决方案
通过跟踪计时器任务ID,在启动新计时前取消旧任务,确保同一时间只有一个计时器在运行。
修改后的完整代码
def medium_level(): global score2, current_image2, total_games, total_w total_games += 1 current_image2 = 0 score2 = 0 timer_id = None # 新增:存储当前计时器任务ID new = Toplevel(window) new.title("Medium Mode") new.configure(background=bg2) new.geometry("600x500") ans = tk.Entry(new, font=('Times', 25)) ans["justify"] = "center" ans["borderwidth"] = "1px" ans.place(x=90, y=270, width=414, height=188) rules2 = tk.Label(new, font=('Times', 20), bg=bg2) rules2["text"] = "Enter Country Name Here:" rules2["justify"] = "center" rules2.place(x=110, y=230) timelbl = tk.Label(new, text="Time: ", font=('Times', 15), bg=bg2) timelbl.place(x=480, y=50) score_label = tk.Label(new, text="Score: 0"+"/12", font=('Times', 15), bg=bg2) score_label.place(x=40, y=50) image_label = tk.Label(master=new) image_label.place(relx=0.30, rely=0.10) image_files = ['bangladesh.png', 'germany.png', 'turkey.png', 'egypt.png', 'madagascar.png','ecuador.png','croatia.png','palestine.png','south africa.png','mongolia.png','peru.png','vietnam.png'] random.shuffle(image_files) def next_image2(): global current_image2, countdown if current_image2 < len(image_files): image_path = image_files[current_image2] image = tk.PhotoImage(file=image_path) image_label.configure(image=image) image_label.image = image current_image2 += 1 start_timer() # 直接调用start_timer,它会重置countdown并取消旧任务 timelbl.config(text=f"Time: {countdown}") else: messagebox.showinfo("Game Over", f"Your score is: {score2}"+"/12") new.quit() def start_timer(): nonlocal timer_id # 访问外层函数的timer_id变量 global countdown # 取消之前未完成的计时器任务 if timer_id is not None: new.after_cancel(timer_id) countdown = 20 update_timer() def update_timer(): nonlocal timer_id global countdown timelbl.config(text=f"Time: {countdown}") if countdown == 0: next_image2() else: countdown -= 1 # 保存新的计时器任务ID,方便后续取消 timer_id = new.after(1000, update_timer) def check_answer2(event): global score2, total_w, countdown user_answer = ans.get().strip().lower() correct_answer = image_files[current_image2 - 1].split('.')[0].lower() if user_answer == correct_answer: score2 += 1 total_w += 1 score_label.config(text=f"Score: {score2}"+"/12") ans.delete(0, tk.END) next_image2() ans.bind('<Return>', check_answer2) next_image2()
关键改动说明
- 新增
timer_id变量:用于记录当前正在运行的计时器任务ID,确保能定位并取消旧任务。 start_timer函数优化:每次启动新计时前,调用new.after_cancel(timer_id)终止之前的计时任务,避免多任务叠加。update_timer函数优化:将new.after()返回的任务ID存入timer_id,为下次取消任务提供依据。
内容的提问来源于stack exchange,提问作者jjk
相关产品推荐
相关产品推荐

