How to know which check box has just been toggled within a mass created checkbox from tkinter or related libraries

Question:

let’s say I’ve this piece of code where it give me a hundred check boxes created by a for loop(I’m working with a switch in customtkinter but it has the same logic as checkbox in tkinter), those check box could either be off or on initially however, I just need to know what is the latest check box that has been toggled, its position or at least what it called so that I could work on it. I’ve done some research but I couldn’t figured out how to work on this, here is the part of that code for the check box, I’ve not assigned the variable to it since I’m trying to figure out the logic first but any help would be much appreciated, thank you!

        with open(r"D:LargecodefileTkinterApplyList1.txt",'r') as f:
        Lines=f.read().splitlines()
    
    for i,val in enumerate(Lines):
        switch = ct.CTkSwitch(master=self.scrollable_framel, text=val,command=self.changestate)
        switch.grid(row=i, column=0, padx=10, pady=(0, 20))
        self.scrollable_frame_switches.append(switch)

The command=self.changestate doesn’t seem to return anything as of right now and it’s just mainly used to run the function and that’s it so I don’t think it’d be of great help either 🙁

Edit: I’m thinking of cross comparing between 2 list of off or on state after a certain event occured for those 100 boxes but that doesn’t seem to be a good idea, and perhaps it’s the same thing for creating 100 function for this purpose as well since it’d take a lot of time to process as the list get longer

Asked By: V21

||

Answers:

You’re on the right track, but you have to set the value of i to a variable the lambda can pass: command=lambda button_index=i: changestate(button_index) – that way the value is updated for each button!

Here’s an example of how to pass the index value i to the event handler function changestate (I’ve removed self here since this isn’t in a class that I can see, but if you’re using a class, just add self.)

def changestate(button_index):
    print(button_index)  # do whatever you want here!


for i, val in enumerate(Lines):
    switch = ct.CTkSwitch(
        master=self.scrollable_framel,
        text=val,
        # pass the latest index value to the lambda for each button
        command=lambda button_index=i: changestate(button_index)
    )
        switch.grid(row=i, column=0, padx=10, pady=(0, 20))
        self.scrollable_frame_switches.append(switch)
Answered By: JRiggles