You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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()

关键修改点

  1. 遍历字典插入条目:不再把整个字典作为单个元素插入,而是遍历labeled_alternatives的每个键值对,将选项格式化为易读的文本后逐个插入Listbox。
  2. 固定初始题目:避免循环覆盖问题,先显示第一道题(如果需要支持多题切换,可以添加按钮实现题目翻页逻辑)。
  3. 添加选中值获取示例:补充了按钮获取选中选项的代码,满足你后续的需求。

内容的提问来源于stack exchange,提问作者Ed_Analyst

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 05:20:28