-1

Hello im trying to create a questionnaire with 5 choises for each question. Since I have lots of questions, I wanted to create labels and radiobuttons in a loop. However, I can not call mainloop() function of tkinter in a loop so when I call it on the outside of the loop, my selection on the questionnaire of any question becomes the answer of the last question. How can I fix this?

def selected(value, question):
    answer_values[question-1] = value
    print(value, question)
        
root = Tk()
root.title('Kişilik Analiz Testi')

answers = {}

for x in range(0, enneagram.shape[0]):
    soru = str(x+1) + ". " + enneagram.SORULAR[x] + " Cümlesi sizi ne kadar iyi ifade ediyor?"
    
    myLabel = Label(root, text = soru).grid(row = x+1, column = 1, sticky = W)
    Label(root, text = "Sorular").grid(row = 0, column = 1, sticky = W)
    Label(root, text = "Çok Zayıf  ").grid(row = 0, column = 2)
    Label(root, text = "Zayıf      ").grid(row = 0, column = 3)
    Label(root, text = "Orta       ").grid(row = 0, column = 4)
    Label(root, text = " İyi       ").grid(row = 0, column = 5)
    Label(root, text = "Çok İyi").grid(row = 0, column = 6)
    
    answers["soru{0}".format(x)] = IntVar()
    answers["soru{0}".format(x)].set(3)
    
   
    button = Radiobutton(root, variable = answers["soru{0}".format(x)], value = 1, command = lambda: selected(1, x+1)).grid(row = x+1, column = 2)
    button = Radiobutton(root, variable = answers["soru{0}".format(x)], value = 2, command = lambda: selected(2, x+1)).grid(row = x+1, column = 3)
    button = Radiobutton(root, variable = answers["soru{0}".format(x)], value = 3, command = lambda: selected(3, x+1)).grid(row = x+1, column = 4)
    button = Radiobutton(root, variable = answers["soru{0}".format(x)], value = 4, command = lambda: selected(4, x+1)).grid(row = x+1, column = 5)
    button = Radiobutton(root, variable = answers["soru{0}".format(x)], value = 5, command = lambda: selected(5, x+1)).grid(row = x+1, column = 6)

root.mainloop()

When I run this cell, i get this window. Default choice is the middle one. When I click on other choices it prints out the index of the last question:

  • There are many questions on this site about looping and giving command. Try `command = lambda y=x+1: selected(1, y)` and so on for all checkbuttons. – Delrius Euphoria Feb 17 '21 at 19:53

1 Answers1

0

Try this code:

import tkinter as tk
from functools import partial


def function(i):
    print("You toggled number %i"%i)
    print([var.get() for var in variables])


root = tk.Tk()
variables = []

for i in range(5):
    # Create the new variable
    variable = tk.IntVar()
    variables.append(variable)

    # Create the command using partial
    command = partial(function, i)

    # Create the radio button
    button = tk.Radiobutton(root, variable=variable, value=i, command=command)
    button.pack()

root.mainloop() 

It uses the partial function/class from functools.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31