首页 > 解决方案 > 将列表框的选定变量的索引存储在列表中

问题描述

我想将列表框中所选变量的所有索引保存在“索引”列表中。有什么解决办法吗?目前我选择了一个变量,它会将它的索引返回给我。我无法选择多个变量并将所有索引保存在列表中。

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)

标签: pythontkinterlistbox

解决方案


默认情况下,您只能选择一项。如果要一次选择多个项目,则需要指定selectmodetotk.MULTIPLEtk.EXTENDED

在你的情况下:

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()

推荐阅读