Amaranth
Amaranth

Reputation: 53

Using <<ListboxSelect>> With More Than One Listbox

I'm trying to use multiple listboxes as a means of displaying a tree of information.

# dictionary: {str : [str]}
dict_ = {some_class.get_dictionary()}
dict_keys = list[dict.keys()]
dict_keys.sort()

def selected_item(val):
    list_box_2.delete(0, END)

    sender = val.widget
    index = sender.curselection()
    value = sender.get(index)

    for thing in dict[value]:
        list_box_2.insert(END, thing)

list_box_1 = Listbox(display_frame, selectmode=SINGLE)
for item in dict_keys:
    list_box_1.insert(END, item)
list_box_1.bind("<<ListboxSelect>>", selected_item)
list_box_1.grid(sticky=W+E+N+S)

def display_selected(val):
    sender = val.widget
    index = sender.curselection()
    value = sender.get(index)
    # here I actually call methods from value, value is a class.
    # this in turn should populate a third list_box but I can't get there.
    print(value)

list_box_2 = Listbox(display_frame, selectmode=SINGLE)
list_box_2.bind("<<ListboxSelect>>", display_selected)
list_box_2.grid(column=0, row=1, sticky=W+E)

List_box_1 works as intended: it displays the dictionary keys, and when the user clicks on one of the items, it populates list_box_2 with the contents of the dictionary at the key selected. However, when I click on items in list_box_2, it calls selected_item() instead of display_selected (or maybe it calls both, hard to tell), but that causes all the content from list_box_2 to get deleted (because of list_box_2.delete(0, END)). I believe this is because of the binding to "<<ListboxSelect>>", but I'm not certain.

Is there some way to achieve the functionality I'm looking for? I've looked around and racked my brain but I can't find any information about this.

Thanks

Upvotes: 2

Views: 545

Answers (1)

jasonharper
jasonharper

Reputation: 9587

You should always include the exportselection=0 option in the Tkinter Listbox, especially when you have more than one of them onscreen at the same time. The default without this option is a bizarre mode in which the list selection is tied to the system clipboard; simultaneous selections in multiple lists simply cannot exist (and you're trashing anything the user might have put in the clipboard themselves).

Upvotes: 4

Related Questions