I've created a couple of listbox widgets where selecting some items in one and then pressing a button below moves the items to the other.
This worked absolutely fine - but I wanted to reuse the container frame because the layouts of the 2 frames was identical (apart from the heading label, and the functions when the buttons were pressed). So I moved all the code except the button functions to a class "ColumnSelector".
However to move data from one "ColumnSelector" to the other I need references to the listboxes inside the instances. Below is the structure of what I would like to do, but I am not sure if this is possible.
I have tried some other ways such as creating the listbox outside of the ColumnSelector class and passing it through, but I ran into problems doing it that way too.
What would be the best way to reference widgets inside instances of other classes?
# Data to be included in second listbox widget
startingSelection = ('Argentina', 'Australia', 'Belgium', 'Brazil', 'Canada', 'China', 'Denmark')
# Two functions performed by the ColumnSelectors
def removeSelected(*args):
idxs = selectedColumns.listBox.curselection() # <- Does not reference correctly
if len(idxs)>=1:
for n in reversed(range(len(idxs))):
idx = int(idxs[n])
item = selectedColumns.listBox.get(idx)
selectedColumns.listBox.delete(idx)
availableColumns.listBox.insert(availableColumns.listBox.size(), item)
def addSelected(*args):
idxs = availableColumns.listBox.curselection() #<- Does not reference correctly
if len(idxs)>=1:
for n in reversed(range(len(idxs))):
idx = int(idxs[n])
item = availableColumns.listBox.get(idx)
availableColumns.listBox.delete(idx)
selectedColumns.listBox.insert(selectedColumns.listBox.size(), item)
# Create ColumnSelectors, pass heading title and function to perform
selectedColumns = ColumnSelector(self, "Columns to include in export", (), removeSelected).grid(column=0, row=0, sticky=(N,W))
availableColumns = ColumnSelector(self, "Available Columns", startingSelection, addSelected).grid(column=1, row=0, sticky=(N,W))
class ColumnSelector(ttk.Frame):
def __init__(self, parent, labelText, startingSelection, function ):
listBox = Listbox(self, height=5, selectmode='multiple')
removeColumnsButton = ttk.Button(self, text="Move", command=function)
#(etc...)