Search code examples
pythonpython-3.xfor-loopvariablestkinter

How to make several variables in for to access them


I tried to create a matrix of checkbuttons and then access all the checkbuttons, but the answer is always 0.

x = dict()
var = dict()
for i in range(1, ex +1):
    for j in range(1, ey +1):
        Label(root, text=i, bg="#B8B8B8").place(x=i*25+ 3, y=10)
        Label(root, text=j, bg="#B8B8B8").place(x=10, y=j*25+ 3)
        var[i, j] = IntVar()
        x[i,j] = var[i, j].get()
        Checkbutton(root, bg="#B8B8B8", variable=var[i,j]).place(x=i*25, y=j*25)

Button(root, text="click", command=lambda: print(x[1, 1]) ).pack()

Solution

  • Because the provided code tries to access the value of the checkbuttons before they have been clicked, it has a problem. x[i,j] = var[i,j] is the line.All the entries in the x dictionary are set to 0 since get() is called before any of the checkbuttons are selected. You can change the lambda function in the Button widget to cycle through every checkbox and output its value in order to access the checkbuttons' values after they have been clicked. Here's an illustration:

    Button(root, text="click", command=lambda: print({(i, j): var[i, j].get() 
    for i in range(1, ex+1) for j in range(1, ey+1)})).pack()