Python tkinter – Display all the checkbuttons selected


I created a GUI with 2 input boxes and a list of checkbuttons (derived from list ‘a’) with scroll. Now, I want to display all the checkbuttons which have been selected.

def sel(x):
    selection = "You selected the option " + str(x)
    label.config(text = selection)
from tkinter import *
import tkinter as tk
from tkinter.scrolledtext import ScrolledText

root = Tk()

Label(root, text='Date from (format: 01-Apr-2022)').place(x=120,y=50)
Label(root, text='Date till (format: 21-Apr-2022)').place(x=120,y=150)
e1 = Entry(root)
e2 = Entry(root),y=50), y=150)

text = ScrolledText(root, width=50, height=60)

label = Label(root), y=450)

b = [IntVar() for x in a[:10]]
for i in range(len(a[:10])):
    cb = tk.Checkbutton(text, text=a[i], variable=b[i], bg='white', anchor='w', onvalue = 1, offvalue = 0, command=sel(a[i]))
    text.window_create('end', window=cb)
    text.insert('end', '\n')


I came up with the code above, but the resultant GUI(below) doesn’t work as intended. It just displays the bottom most checkbutton even without selecting it. Further, selecting or unselecting any other checkbutton has no effect whatsoever.

>Solution :

Using a sample list for list a, since you have not provided it in the question.


Since you are providing an argument to your function, you can use python lambdas.
Currently, you are not passing a function to the command attribute of CheckButton, instead you are passing the returned value of sel().



Instead of passing the name as an argument to the function, you can iterate the list of IntVars and decide which ones are selected.

import tkinter as tk
from tkinter.scrolledtext import ScrolledText

root = tk.Tk()

def refresh():
    selected = []
    for i in range(len(a)):
        if b[i].get():
    if len(selected) > 1:
        label.config(text=(", ".join(selected) + " are selected"))
    elif len(selected) == 1:
        label.config(text=(selected[0] + " is selected"))

tk.Label(root, text='Date from (format: 01-Apr-2022)').place(x=120,y=50)
tk.Label(root, text='Date till (format: 21-Apr-2022)').place(x=120,y=150)
e1 = tk.Entry(root)
e2 = tk.Entry(root),y=50), y=150)

text = ScrolledText(root, width=50, height=60)

label = tk.Label(root), y=450)

a = ["test1", "test2", "test3", "test4"]
b = []

for i in a:
    var = tk.IntVar()
    cb = tk.Checkbutton(text, text=i, variable=var, bg='white', anchor='w', onvalue=1, offvalue=0, command=refresh)
    text.window_create('end', window=cb)
    text.insert('end', '\n')


Leave a Reply Cancel reply