I got the idea of binding a function to a Listbox
from this link:
Getting a callback when a Tkinter Listbox selection is changed?
This works very well using one Listbox
only.
As soon as I tried to introduce a second Listbox
on the page and also bind it to a second function the functionality like I imagined was gone.
Apparently selecting an item in the second list while an item in the first list is already selected will remove the selection from list one. Can any one help me fix that behavior?
here is my sample code:
import tkinter as tk
window = tk.Tk()
#generic window size, showing listbox is smaller than window
window.geometry("600x480")
frame = tk.Frame(window)
frame.pack()
def select(evt):
event = evt.widget
output = []
selection = event.curselection()
#.curselection() returns a list of the indexes selected
#need to loop over the list of indexes with .get()
for i in selection:
o = listBox.get(i)
output.append(o)
print(output)
def select2(evt):
event = evt.widget
output = []
selection = event.curselection()
#.curselection() returns a list of the indexes selected
#need to loop over the list of indexes with .get()
for i in selection:
o = listBox.get(i)
output.append(o)
print(output)
listBox = tk.Listbox(frame, width=20, height = 5, selectmode='multiple')
listBox.bind('<<ListboxSelect>>',select)
listBox.pack(side="left", fill="y")
scrollbar = tk.Scrollbar(frame, orient="vertical")
scrollbar.config(command=listBox.yview)
scrollbar.pack(side="right", fill="y")
listBox.config(yscrollcommand=scrollbar.set)
for x in range(100):
listBox.insert('end', str(x))
listBox2 = tk.Listbox(frame, width=20, height = 5, selectmode='multiple')
listBox2.bind('<<ListboxSelect>>',select2)
listBox2.pack(side="left", fill="y")
scrollbar2 = tk.Scrollbar(frame, orient="vertical")
scrollbar2.config(command=listBox.yview)
scrollbar2.pack(side="right", fill="y")
listBox2.config(yscrollcommand=scrollbar.set)
for x in range(100):
listBox2.insert('end', str(x))
window.mainloop()
You just need to add the parameter exportselection=False
when you create your listboxes tk.Listbox(frame,...)
. Then your listboxes will keep being selected.
listBox = tk.Listbox(frame, width=20, height = 5, selectmode='multiple', exportselection=False)
listBox2 = tk.Listbox(frame, width=20, height = 5, selectmode='multiple', exportselection=False)