How to keep selections highlighted in a tkinter Listbox?

Question:

I have 2 separated List-boxes set on single selection mode. When I select an item from listboxA, it gets highlighted, but when I select an item from listboxB, it gets highlighted, and the item from listboxA remains active, but isn’t highlighted. How can I keep both highlighted?

Asked By: Mission Impossible

||

Answers:

Short answer: set the exportselection attribute of each listbox to False

Tkinter has its roots in the X windowing system. X has a concept called a “selection”, which is similar to the system clipboard (more accurately, the clipboard is the “PRIMARY” selection). By default, several of the tkinter widgets export their selection to be the PRIMARY selection. An application can only have one PRIMARY selection at a time, which is why the highlight disappears when you click between two listboxes.

Tkinter gives you control over this behavior with the exportselection configuration option for the listbox (and text and entry widgets). Setting it to False prevents the export of the selection to the X selection, allowing the widget to retain its selection when a different widget gets focus.

For example:

the_listbox = tk.Listbox(..., exportselection=False)

Quoting from the official tk documentation:

exportselection
Specifies whether or not a selection in the widget should also be the
X selection. The value may have any of the forms accepted by
Tcl_GetBoolean, such as true, false, 0, 1, yes, or no. If the
selection is exported, then selecting in the widget deselects the
current X selection, selecting outside the widget deselects any widget
selection, and the widget will respond to selection retrieval requests
when it has a selection. The default is usually for widgets to export
selections.

Answered By: Bryan Oakley
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.