4

I have a program where I need to take a selection from Tkinter.Listbox and an entry field and do something with that data. However, if I highlight any text within the entry field (i.e., to delete previous entry), the Listbox selection is cleared. How can I overcome it so that the Listbox selection persists?

import Tkinter as tk

master = tk.Tk()
listbox = tk.Listbox(master)
listbox.grid(row=0, column=0)
items = ['a', 'b', 'c']
for item in items:
    listbox.insert(tk.END, item)

efield = tk.Entry(master)
efield.grid(row=1, column=0)

tk.mainloop()

Steps to reproduce:

  1. Type something in the entry field.

  2. Select something in the listbox.

  3. Highlight whatever you entered in the entry field => selection in the listbox gets cleared.


This related question with similar issue How to select at the same time from two Listbox? suggests to use exportselection=0, which doesn't seem to work for me. In such case selection = listbox.selection_get() throws an error while the right line is still highlighted.

Community
  • 1
  • 1
sashkello
  • 17,306
  • 24
  • 81
  • 109

2 Answers2

4

I know this is an old question, but it was the first google search result when I came across the same problem. I was seeing odd behavior using 2 list boxes when using selection_get() and also the selection persistence issue.

selection_get() is a universal widget method in Tkinter, and was returning selections that were last made in other widgets, making for some really strange behavior. Instead, use the ListBox method curselection() which returns the selected indices as a tuple, then you can use the ListBox's get(index) method to get the value if you need.

To solve the persistence issue, set exportselection=0 when instantiating the ListBox instance.

list_box = tk.Listbox(master, exportselection=False)

...

selected_indices = list_box.curselection()
first_selected_value = list_box.get(selected_indices[0])
Fiver
  • 9,909
  • 9
  • 43
  • 63
  • 3
    Using `exportselection=0` on `Listbox` did the trick for me. I don't understand the downvote. – z80crew Mar 11 '20 at 17:16
0

As for now, I wasn't able to cleanly overcome the problem. One way around is to create a variable which will store the selected list value on click:

selected = None
def onselect(e):
    global selected
    selected = listbox.selection_get()

listbox.bind('<<ListboxSelect>>', onselect)

This doesn't keep the highlight, but the selection is now stored in a variable and can be used further.

sashkello
  • 17,306
  • 24
  • 81
  • 109