Make Some Tkinter Listbox Items Always Selected
<p>I have a tkinter listbox where some of the items in the listbox need to always be selected. In my app, these items are required by the user, whereas some other items in the listbox are optional (should be selectable/deselectable).</p>

<p>Most examples bind a function using <code>'&lt;&lt;ListboxSelect&gt;&gt;'</code>.</p>

<p>What I don't understand is, how do I get the exact single item the user selected from the bind event?</p>

<p>In my example code, <code>apples</code>, <code>peaches</code>, <code>lettuce</code> are selected initially. Let's say I click on <code>apples</code>. Normally this event would unselect <code>apples</code> but I want my function to run and set the selection on <code>apples</code> so it looks artificially like it's not able to be unselected.</p>

<pre><code>import tkinter as tk

root = tk.Tk()

requiredlb = tk.Listbox(root, exportselection=False, activestyle='none', selectmode=tk.MULTIPLE)
for i,item in enumerate(['apples', 'oranges', 'peaches', 'carrots', 'lettuce', 'grapes']):
  requiredlb.insert(tk.END, item)
  if i % 2 == 0:
    requiredlb.selection_set(i)
requiredlb.grid(row=6, column=1, sticky='ew')

def always_selected(event):
  widget = event.widget
  ## What Goes Here? ##

requiredlb.bind('&lt;&lt;ListboxSelect&gt;&gt;', func=always_selected)

root.mainloop()
</code></pre>

<p>Ok, nice question. Here is a workaround I managed to come up with, and it seems to work.</p>

<p>First, create a list of indices you want to always keep selected:</p>

<pre><code>items = ['apples', 'oranges', 'peaches', 'carrots', 'lettuce', 'grapes']
special_items = [0, 2, 4]

for i,item in enumerate(items):
    ...
</code></pre>

<p>As you can see I modified a bit your code</p>

<p>Then in the event function always make sure those indices are selected by selecting them explicitly:</p>

<pre><code>def always_selected(event):
  widget = event.widget
  for idx in special_items:
      widget.selection_set(idx)
</code></pre>

python tkinter listbox bind