Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep selections highlighted in a tkinter Listbox?

Tags:

python

tkinter

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?

like image 492
Mission Impossible Avatar asked Apr 06 '12 19:04

Mission Impossible


People also ask

Which method is used to add elements in listbox tkinter?

set () method of the vertical scrollbar.

What is the default selection mode of a listbox widget?

The default is SUNKEN. The background color to use displaying selected text. BROWSE − Normally, you can only select one line out of a listbox. If you click on an item and then drag to a different line, the selection will follow the mouse.

How many items does a listbox hold by default?

The default is 20. If you want to allow the user to scroll the listbox horizontally, you can link your listbox widget to a horizontal scrollbar. Set this option to the . set method of the scrollbar.

How do I update a listbox in Python?

To edit the Listbox items, we have to first select the item in a loop using listbox. curselection() function and insert a new item after deleting the previous item in the listbox. To insert a new item in the listbox, you can use listbox. insert(**items) function.


1 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.

like image 86
Bryan Oakley Avatar answered Sep 27 '22 21:09

Bryan Oakley