I just forayed into tkinter for the first time and am running into some issues. I want to display several lists to users, and store their selections for each list in a dictionary (used to filter several columns of a dataframe later). Suppose, for instance, there are two lists: 1) One labeled "Brand", containing 'Brand X' and 'Brand Y' as options, 2) another "Customer Type", containing "New," "Existing," "All."
In sum, when all is said and done, if a user picks "Brand X", "New", and "All", then I'd get a dictionary back of {'Brand':['Brand X'],'Customer Type':['New','All']}. Getting one list is easy... but looping through the lists is presenting problems.
I have the below code so far:
from tkinter import *
from tkinter import ttk
class checkList(Frame):
def __init__(self, options, parent=None):
Frame.__init__(self, parent)
self.makeHeader()
self.options = options
self.pack(expand=YES, fill=BOTH, side=LEFT)
self.makeWidgets(self.options)
self.selections = []
def makeHeader(self):
header = ttk.Label(self,text='Please select options to limit on.')
header.pack(side=TOP)
self.header = header
def makeWidgets(self, options):
for key in self.options.keys():
lbl = ttk.Label(self, text=key)
lbl.pack(after=self.header)
listbox = Listbox(self, selectmode=MULTIPLE, exportselection=0)
listbox.pack(side=LEFT)
for item in self.options[key]:
listbox.insert(END, item)
listbox.bind('<<ListboxSelect>>', self.onselect)
self.listbox = listbox
def onselect(self, event):
selections = self.listbox.curselection()
selections = [int(x) for x in selections]
self.selections = [self.options[x] for x in selections]
if __name__ == '__main__':
options = {'Brand':['Brand','Brand Y'], 'Customer Type': ['All Buyers','New Buyers','Existing Buyers']}
checkList(options).mainloop()
Needless to say, the [self.options[x] for x in selections] works great with just one list, but since I have a dictionary, I really need [self.options[key][x] for x in selections]. However, I can't figure out how to pass the key at any given point in the loop. Is there a way to achieve what I'm trying to do?