Python (Tkinter) – Creates a list of checkboxes from a list box
I want to create a checkbox list for each list box item. So I created a list box with 4 different items, “One”, “Two”, “Three”, “Four”. I want to list the corresponding checkbox items for each list box entry. When I click on a list box entry, it should have a list of checkboxes to the right of it, and when I click on another list box entry, it should have a list of checkboxes independent of the other list box items. All checkbox lists are independent of each other, which means you can check 4 checkboxes when you select the first list box entry, but when I select the second list box entry, it should show 0 checked content (because they are independent).
import tkinter
from tkinter import *
master = tkinter. Tk()
master.geometry("750x500")
listbox = Listbox(master)
listbox.place(x=3,y=0)
for item in ["one", "two", "three", "four"]:
listbox.insert(END, item)
enable = {'button 1','button 2', 'button 3'}
def onselect(evt):
# Note here that Tkinter passes an event object to onselect()
w = evt.widget
x=0
index = int(w.curselection()[0])
value = w.get(index)
print ('You selected item %d: "%s"' % (index, value))
for item in enable:
checkboxes = Checkbutton(master, text=item, variable=item)
checkboxes.place(x=300,y=0+x)
x+=50
listbox.bind('<<ListboxSelect>>', onselect)
print(enable)
mainloop()
Solution
Interesting question, I’ve been studying it for 30 minutes. Of course there are several methods, here it is probably the shortest and most dynamic :
#!/usr/bin/env python3
import tkinter
from tkinter import *
master = tkinter. Tk()
master.geometry("750x500")
listbox = Listbox(master)
listbox.place(x=3,y=0)
enable = ['button 1', 'button 2', 'button 3']
list_for_listbox = ["one", "two", "three", "four"]
for item in list_for_listbox:
listbox.insert(END, item)
for y in enable:
globals()["var{}{}".format(item, y)] = BooleanVar()
globals()["checkbox{}{}".format(item, y)] = Checkbutton(master, text=y, variable=globals()["var{}{}".format(item, y)])
def onselect(evt):
# Note here that Tkinter passes an event object to onselect()
w = evt.widget
x=0
index = int(w.curselection()[0])
value = w.get(index)
print ('You selected item %d: "%s"' % (index, value))
for y in enable:
for item in list_for_listbox:
globals()["checkbox{}{}".format(item, y)].place_forget()
globals()["checkbox{}{}".format(value, y)].place(x=300,y=0+x)
x+=50
listbox.bind('<<ListboxSelect>>', onselect)
print(enable)
mainloop()
You can access variables via globals()[“var{}{}".format(item, y)].
Example:
for item in list_for_listbox:
for y in enable:
print(item + " [" + y + "] " + str(globals()["var{}{}".format(item, y)].get()))