使用after方法时Tkinter窗口崩溃,GUI无法显示求助
问题修复方案
你的代码存在多个核心问题导致GUI无法显示、逻辑阻塞,以下是修复后的完整代码,以及关键问题的说明:
修复后的代码
import tkinter as tk app = tk.Tk() app.title("Vacation MadLibs") # 存储答案的列表 answers = [] # 问题列表 questions = [ "Name an emotion.... ", "Name a place.... ", "Name a person.... ", "Name a vehicle.... ", "Name a number.... ", "Name another number.... ", "Name a verb.... ", "Name an adjective.... ", "Name an animal... ", "Name another adjective.... ", "Name a food... ", "Name an emotion... ", "Name a famous person.... ", "Name an adjective.... " ] current_question = 0 def help(): helpWindow = tk.Toplevel(app) # 用三引号包裹多行文本 tk.Label(helpWindow, text="""How to play: This game is called MadLibs! You will be asked a series of questions that you will have to answer. After you are done answering the questions we will show you a story that you created!""").pack() tk.Button(app, text="How to play", command=help).pack() label = tk.Label(app, text="") label.pack() textbox = tk.Text(app, height=1, width=30) textbox.pack() def show_story(): # 生成并显示故事 story = f"""This is your story... Im so {answers[0]} Today we are going on a vacation to {answers[1]} Im going with {answers[2]} and we will travel there by {answers[3]} The journey will take {answers[4]} hours and we will stay there for {answers[5]} days. After we arrived we decided to {answers[6]} Then we saw a {answers[7]} {answers[8]} We were starving so we decided to eat a {answers[9]} {answers[11]} We were so {answers[10]} Because we met {answers[12]} Overall the vacation was really {answers[13]}""" # 用弹窗显示故事 story_window = tk.Toplevel(app) tk.Label(story_window, text=story, justify="left").pack(padx=10, pady=10) # 清空输入框和标签,重置问题 global current_question current_question = 0 answers.clear() label["text"] = questions[current_question] def submit_answer(): global current_question # 获取输入并去除换行符和空格 answer = textbox.get("1.0", "end").strip() if answer: answers.append(answer) textbox.delete("1.0", "end") current_question += 1 if current_question < len(questions): label["text"] = questions[current_question] else: # 所有问题完成,显示故事 show_story() button = tk.Button(app, text="提交答案", command=submit_answer) button.pack() # 显示第一个问题 label["text"] = questions[current_question] # 启动主循环 app.mainloop()
关键问题修复说明
- 缺少主循环:原代码没有调用
app.mainloop(),这是Tkinter窗口显示的核心,必须添加才能启动GUI事件循环。 - 同步调用阻塞逻辑:原代码直接循环调用
getInput,会阻塞Tkinter的事件处理,改为用问题列表+事件驱动的方式,每次提交答案后自动切换下一个问题。 - 输入处理不规范:原代码获取的Text内容包含换行符,用
.strip()去除多余字符,确保答案干净。 - 按钮无文本:原Button没有设置
text参数,用户无法识别点击按钮的作用,添加"提交答案"文本。 - 多行字符串错误:help函数里的Label文本用单行引号包裹多行内容会报错,改为三引号
"""包裹。 - 故事生成时机错误:原代码在GUI启动前就打印故事,此时还没有任何输入,改为所有问题完成后再生成并显示故事。
- 全局变量逻辑混乱:原代码用
d全局变量处理输入,但没有正确重置和流转,改为用answers列表存储答案,current_question跟踪当前问题索引。
内容的提问来源于stack exchange,提问作者windows.sys
相关产品推荐
相关产品推荐

