majesty
majesty

Reputation: 27

Tkinter checkbox issue

I'm trying to create a Tkinter GUI where I have checkboxes for items, but I got only one (last one).

What am I doing wrong?

class Items(Daily):
    def __init__(self):
        super().__init__()
        self.appD=Frame(self.root, padx=20, pady=20)
        self.appD.grid(row=0, column=0)
        self.itemsAl()


    def itemsAl(self):
        items=['item1', 'item2', 'item3']
        variable=IntVar()
        check_boxes={item: IntVar() for item in items}

        label_Lbl=Label(self.appD, text='label', )
        label_Lbl.grid(row=0, column=0, sticky=W)

        for item in items:
            c=Checkbutton(self.appD, text=item, variable=item)
        for x in range(1, 3):
            c.grid(row=x, column=0, sticky=W)

        button_Done=Button(self.appD, text='Done')
        button_Done.grid(row=4, column=0, sticky=W)

        self.root.mainloop()

Upvotes: 1

Views: 37

Answers (1)

James
James

Reputation: 36608

You are over-writing the value of c with each iteration, so you only end up saving the last value. Try saving the checkboxes to a list and then iterate over that list.

class Items(Daily):
    def __init__(self):
        super().__init__()
        self.appD=Frame(self.root, padx=20, pady=20)
        self.appD.grid(row=0, column=0)
        self.itemsAl()


    def itemsAl(self):
        items=['item1', 'item2', 'item3']
        variable=IntVar()
        check_boxes={item: IntVar() for item in items}

        label_Lbl=Label(self.appD, text='label', )
        label_Lbl.grid(row=0, column=0, sticky=W)

        cboxes = [
            Checkbutton(self.appD, text=item, variable=item) for item in items
        ]
        for r, c in enumerate(cboxes, 1)
            c.grid(row=r, column=0, sticky=W)

        button_Done=Button(self.appD, text='Done')
        button_Done.grid(row=4, column=0, sticky=W)

        self.root.mainloop()

Upvotes: 1

Related Questions