Tkinter列表框中测验选项显示为一行的修复方法问询
问题解决:Tkinter Listbox选项显示为一行的修复
你的问题出在将整个字典作为单个元素插入Listbox,导致所有选项被合并成一行显示。以下是具体修复步骤和优化后的代码:
问题分析
labeled_alternatives是一个键值对字典(比如{'a': 'Tuesday', 'b': 'Monday', ...}),而你把它放到列表my_list=[labeled_alternatives]中,循环插入时只添加了这一个字典元素,Listbox会直接打印整个字典的字符串形式,所以所有选项挤在一行。- 另外,当前代码遍历题目时会覆盖
Question_Label和labeled_alternatives,最终只会显示最后一道题的内容,这个问题也可以一并优化。
修复代码
from tkinter import * import random from string import ascii_lowercase QuizFrame = Tk() NUM_QUESTIONS_PER_QUIZ = 4 QUESTIONS = { "What day of the week is it?": [ "Monday", "Tuesday", "Wednesday", "Thursday" ], "What is the first state?": [ "Delaware", "Maryland", "Texas", "Maine" ], } num_questions = min(NUM_QUESTIONS_PER_QUIZ, len(QUESTIONS)) questions = random.sample(list(QUESTIONS.items()), k=num_questions) Question_Label = Label(QuizFrame, text="", font=("Helvetica", 20)) Question_Label.grid(row=3, column=1) # 初始化当前题目,避免循环覆盖问题 current_question_idx = 0 question, alternatives = questions[current_question_idx] Question_Label.config(text=question) correct_answer = alternatives[0] labeled_alternatives = dict( zip(ascii_lowercase, random.sample(alternatives, k=len(alternatives))) ) my_listbox=Listbox(QuizFrame, width=30, height=4) my_listbox.grid(row=6, column=1) # 遍历字典,将每个选项作为单独条目插入Listbox for label, option in labeled_alternatives.items(): # 格式化为"a. Monday"的测验题样式 list_item = f"{label}. {option}" my_listbox.insert(END, list_item) # 示例:添加按钮获取选中值 def get_selected(): selected_indices = my_listbox.curselection() if selected_indices: selected_item = my_listbox.get(selected_indices[0]) print(f"选中选项:{selected_item}") select_btn = Button(QuizFrame, text="获取选中值", command=get_selected) select_btn.grid(row=7, column=1) QuizFrame.mainloop()
关键修改点
- 遍历字典插入条目:不再把整个字典作为单个元素插入,而是遍历
labeled_alternatives的每个键值对,将选项格式化为易读的文本后逐个插入Listbox。 - 固定初始题目:避免循环覆盖问题,先显示第一道题(如果需要支持多题切换,可以添加按钮实现题目翻页逻辑)。
- 添加选中值获取示例:补充了按钮获取选中选项的代码,满足你后续的需求。
内容的提问来源于stack exchange,提问作者Ed_Analyst
相关产品推荐
相关产品推荐

