Reputation: 35
I would like to save in an "indice" list all the indexes of the variables selected in the listbox. Any solution? At the moment I select a variable and it returns its index to me. I am not able to select multiple variables and save all indices in a list.
import tkinter as tk
from tkinter.constants import RIGHT, VERTICAL, Y
Ch_Output = ["a","b","c","d","e","f"]
root = tk.Tk()
root.title('Seleziona canale')
root.geometry("400x500")
var_select = str()
indice = int()
def getElement(event):
selection = event.widget.curselection()
index = selection[0]
value = event.widget.get(index)
result.set(value)
print('\n',index,' -> ',value)
global var_select
global indice
var_select = value
indice = index
#root.destroy()
# scroll bar-------
result =tk.StringVar()
my_frame = tk.Frame(root)
my_scrollbar = tk.Scrollbar(my_frame, orient=VERTICAL)
var2 = tk.StringVar()
var2.set(Ch_Output)
# list box-----------
my_listbox = tk.Listbox(my_frame, width=50, height=20, listvariable=var2)
# configure scrolbar
my_scrollbar.config(command=my_listbox.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
my_frame.pack()
my_listbox.pack(pady=15)
my_listbox.bind('<<ListboxSelect>>', getElement) #Select click
root.mainloop()
print('\n',indice)
Upvotes: 0
Views: 434
Reputation: 3089
By default, you can select only one item. If you want to select multiple items at once you need to specify selectmode
to tk.MULTIPLE
or tk.EXTENDED
.
In your case:
import tkinter as tk
from tkinter.constants import RIGHT, VERTICAL, Y, MULTIPLE
...
selected_index = []
def getElement(event):
global selected_index
selected_index = list(event.widget.curselection())
print(selected_index)
print("Values: ", [event.widget.get(x) for x in selected_index])
...
my_listbox = tk.Listbox(my_frame, width=50, height=20, listvariable=var2, selectmode=MULTIPLE)
...
root.mainloop()
Upvotes: 2