lundi 15 juillet 2019

TKinter CheckButtons won't properly update values

I know this question has been asked a few times, but not one of the other solutions has applied to my problem.

I have a variable list of "anomalies" stored as a tuple holding the anomaly name and either a 0 or 1, determining whether or not to notify the user of something. Because the list is of variable length, the checkbuttons need to be created in a for loop.

I want to create a popup that shows a list of checkbuttons, to allow the user to edit the notification values to their preference. However, the implementation of this idea that I've used causes the checkbuttons to not change the value of their variables or display the proper on/off state.

Here's my code:

notif_anoms = [("Anomaly 1", 1), ("Anomaly 2", 0)]
checkbox_vars = []

    def select_desired_anomaly_checks(self):
        popup = Tk()
        popup.wm_title("Desired Anomalies")
        len_a = len(self.notif_anoms)

        for i in range(0, len_a):
            msg, on = self.notif_anoms[i]

            self.checkbox_vars.append(IntVar(value=on))
            self.checkbox_vars[-1].set(on)

            tk.Checkbutton(popup, text=msg, variable=self.checkbox_vars[-1], onvalue=1, offvalue=0, command=self.update_vars).grid(row=i, sticky=W)
        popup.resizable(0, 0)
        popup.mainloop()

    def update_vars(self):
        for i in range(0, len(self.checkbox_vars)): 
            var = self.checkbox_vars[i]
            print(var.get())
            self.notif_anoms[i] = (self.notif_anoms[i][0], var.get())
        print('------------------')

The only problem I can think of with this is that I'm setting the IntVar inside of the for loop, but as far as I can think of, there's no other way to create a list of checkboxes at runtime with unknown length.

Any and all help is appreciated, thank you.




Aucun commentaire:

Enregistrer un commentaire