Home > Software design >  Quiz listbox items displaying in one line
Quiz listbox items displaying in one line

Time:11-11

I am trying to show the options for quiz questions in a listbox. The value will later be retrieved with a button. They show as one line instead of different listed items. I think it has something to do with the list and how it is formatted, but I am not sure how to fix this. How can I fix this?

from tkinter import *
from random import randint
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)

for num, (question, alternatives) in enumerate(questions, start=1):
    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)
my_listbox.grid(row=6, column=1)

my_list=[labeled_alternatives]

for item in my_list:
    my_listbox.insert(END,item) 


QuizFrame.mainloop()

CodePudding user response:

my_list only contains one item, labeled_alternative, so when you iterate it in the for loop, the entire dictionary gets inserted. Instead, you want to iterate labeled_alternatives.items() to get the keys and values for each item in your dictionary. Change the for loop to

for k, v in labeled_alternatives.items():
    my_listbox.insert(END, k   ": "   v) 
  • Related