Detect automatic item selection in a Listbox using Tkinter
<p>I mean, for Buttons you can write something like this:  </p>

<pre><code>def addItem():
    pass
addbtn = Button(mainFrame, text = "Add Item", command = addItem)
</code></pre>

<p>How can I do the same thing for a Listbox? Like this one for example:</p>

<pre><code>def on_selection():
    pass
list = Listbox(mainFrame, selectmode = SINGLE, command = on_selection) # This doesn't work.
</code></pre>

<p>The point is that the binding <code>mainFrame.bind("&lt;&lt;ListboxSelect&gt;&gt;", on_selection)</code> <strong>doesn't works when I select an item automatically with <code>list.selection_set(selection)</code></strong>.</p>

<p>In other words <strong>automatically trigger the on_selection() function when list.selection_set(...) is called</strong> without overwriting the Listbox class or selection_set function. The goal is to write one line instead of </p>

<pre><code>list.selection_set(selct)
on_selection()
</code></pre>

<p>every time.</p>

<p>Is there a way to do this?</p>

<pre><code>import tkinter as tk

root = tk.Tk()

def on_selection(event):
  print(dir(event))

def some_nonevent():
  print(str(2 + 2))

listbox = tk.Listbox(root, selectmode=tk.SINGLE, activestyle='none')
for name in ['john', 'tim', 'sam', 'jill', 'sandra']:
  listbox.insert(tk.END, name)

listbox.bind('&lt;&lt;ListboxSelect&gt;&gt;', on_selection)

listbox.selection_set(3)

listbox.grid()

with open('myfile.py') as f:
  contents = f.read()
  if '\nlistbox.selection_set(2)\n' in contents:
    listbox.event_generate('&lt;&lt;ListboxSelect&gt;&gt;')
    some_nonevent()
  else:
    print('do nothing')

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

python events tkinter listbox