1

Apologies if this has been asked before (and if my code is bad, I'm a novice coder), but as part of an assignment, I've been tasked with writing a simple quiz in Python. Using TkInter, I use the following code to generate radio buttons with the answers that the user can select, using input pulled from a dictionary.

# Dictionary to create multiple buttons

values = {
    "Pong": 0,
    "Spacewar!": 1,
    "Tetris": 2,
    "Snake": 3
}

# Question

theQuestion = "Wat is de eerste videogame ooit gemaakt?"

# Detect which button is selected

def quiz_processAnswer():
    print(values.get(answers))

# Loop is used to create multiple Radiobuttons
# rather than creating each button separately

for (answers, num) in values.items():
    Radiobutton(
        master, text = answers,
        variable     = v,
        value        = num,
        indicator    = 0,
        background   = "darkslategray",
        fg           = "goldenrod",
        command      = quiz_processAnswer
    ).pack(fill = X, ipady = 5)

The script would determine what answer the user selects using the key; e. g. values.gets("Tetris") works and returns 2 when the user clicks on a button. I want the script to be able to determine the value through a variable; so that if you click Snake, it returns 3; if you click Tetris, it returns 2; etc.

I've tried passing values, answers, num, v, just about everything. Passing answers as parameter always leads to 3 being returned, even when I click an answer that isn't Snake. How would I go about this?

  • 1
    Just use `command = lambda answers=answers: quiz_processAnswer(answers)` and change your `def` to `def quiz_processAnswer(answers):`. Function bodies are late-binding so `values.get(answers)` refers to the last value of `answers` in your loop. – Axe319 Nov 18 '21 at 14:44
  • [This](https://stackoverflow.com/questions/27198287/tkinter-create-multiple-buttons-with-different-command-function) is sort of related but not directly since you are missing the `lambda` step. But the key concept remains the same. – Axe319 Nov 18 '21 at 14:51

0 Answers0