Tkinter ListBox Virtual binding applied to multiple choices
The concept of virtual binding can also be applied to multiple selections, which will be explained directly with examples below.
Example#1
When multiple items are selected, those selected items will be printed out. This program uses EXTENDED for selectmode.
from tkinter import *
def itemSelected(event): # List the selected single item
obj = event.widget # Get the object of the event, i.e. the Listbox control object
indexs = obj.curselection() # Get Index
# print(index)
# print(type(obj.get(index)))
# print(obj.get(index))
# var.set(obj.get(index)) # Set label content
for index in indexs:
print(obj.get(index))
print("-------------")
fruits = [
"Banana","Watermelon","Pineapple",
"Orange","Grapes","Mango"
]
root = Tk()
root.title("apidemos.com")
root.geometry("300x250")
var = StringVar()
# var.set("cxq123")
lab = Label(root,text="",textvariable=var)
lab.pack(pady=5)
lb = Listbox(root,selectmode=EXTENDED)
for fruit in fruits:
lb.insert(END,fruit)
lb.bind("<<ListboxSelect>>",itemSelected)
lb.pack(pady=5)
root.mainloop()
Output:
The following is the output of the Python Shell window.