Removing Selected Items From The Listbox And From The List
Solution 1:
For my listboxes, I generally have the mode set to EXTENDED
so that users can select one or more items and remove all at once. I do so via the following method:
# Function with Tk.Listbox passed as arg
def remove_from(list_box):
# Tuple of currently selected items in arg
selected_items = list_box.curselection()
# Initialize a 'repositioning' variablepos = 0for item in selected_items:
# Set index of each item selected
idx = int(item) - pos# Deletes only that index in the listbox
list_box.delete(idx, idx)
# Increments to account for shiftspos += 1
For example, lets say in my listbox I had 4 items. I then select the first item and the third item. By calling list_box.curselection()
I've received the following:
selected_items = (0, 2)
Where 0
is the first item's position in the listbox, and 2
is the third item's position. Then for each item in my tuple, I establish its index.
Walking through this, for the first item the following takes place:
idx = 0 - 0
list_box.delete(0, 0)
pos = 1
So now I have deleted the item at position 0
(e.g. the first item) and my listbox has shifted! So the second is now the first, third is the second and fourth is the third. However, my tuple has not changed as it was the positions in the listbox of the original selection. This is key. What happens next is:
idx = 2 - 1
list_box.delete(1, 1)
pos = 2
Since the listbox shifted, position 1
now corresponds to the item that was originally in the third position of the listbox. This can continue for n
positions.
For self.words removal
You could try the following:
# Function with Tk.Listbox and self.words[] passed as args
def remove_from(list_box, list):
# Tuple of currently selected items in arg
selected_items = list_box.curselection()
# List of Words already constructed
word_list = list
# Initialize a 'repositioning' variablepos = 0for item in selected_items:
# Set index of each item selected
idx = int(item) - pos# Deletes only that index in the listbox
list_box.delete(idx, idx)
# Gets the string value of the given index
word = list_box.get(idx, idx)
# Removes the word from the listif any(word in xforx in word_list):
word_list.remove(word)
# Increments to account for shiftspos += 1
Post a Comment for "Removing Selected Items From The Listbox And From The List"