Search code examples
python-3.xtkintertkinter-entry

How can I print total clicked number of checkboxes within a function in tkinter?


I am trying to create a function inside a class and with this function, I want to calculate how many checkboxes clicked.

# This function assesses number of clicked items in my class's list
    def badper(self):
        window=Tk()
        window.config(bg='lightgreen')
        # total = 0
        def show(self):
            new_label = Label(window, text=var.get()).pack()
        var=IntVar()
        def create_check_button(self,i):
            var = IntVar()
            c=Checkbutton(window,text=self.badcharacter[i],variable=var)
            c.pack()
            # if c == 1:
            #     global total
            #     total += 1
        # This loop creates checkboxes in the equivalent of number items of my list
        for i in range(6):
            create_check_button(self,i)

        # This button should show how many items clicked so far
        my_button=Button(window,text="show", font=("Arial", 12, "bold"),command=show(self)).pack()

Solution

  • This code achieves the correct outcome with the total number of set Checkbuttons displayed.

    Remarks in code explain the problems in this simplified snippet.

    import tkinter as tk
    
    window = tk.Tk()
    window.config(bg='lightgreen')
    
    store_var = []
    
    def show():
        total = 0
        # This is one way to display results
        for a in store_var:
            if a.get():
                total = total + 1
        my_label["text"] = f"Total = {total}"
    
    def create_check_button(i):
        var = tk.IntVar()
        # no information on badcharacter list supplied
        c = tk.Checkbutton(
            window, text = i, onvalue = 1, offvalue = 0, variable = var)
        c.pack()
        # Save each IntVar in list for use by function show()
        store_var.append(var)
    
    for i in range(6):
        create_check_button(i)
    
    # my_label is referenced in function show() so define my_label separately from pack
    my_label = tk.Label(window, text = "Output")
    my_label.pack()
    
    # Button is not referenced anywhere so combining declaration and pack management is OK
    tk.Button( window, text = "show", font = "Arial 12 bold", command = show).pack()
    
    window.mainloop()