python - 将列表框的选定变量的索引存储在列表中
问题描述
我想将列表框中所选变量的所有索引保存在“索引”列表中。有什么解决办法吗?目前我选择了一个变量,它会将它的索引返回给我。我无法选择多个变量并将所有索引保存在列表中。
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)
解决方案
默认情况下,您只能选择一项。如果要一次选择多个项目,则需要指定selectmode
totk.MULTIPLE
或tk.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()
推荐阅读
- android - 测试房间数据库,可迭代包含“项目”但!项目 0 是“项目”
- javascript - 你什么时候在反应中使用类组件,因为 useState 现在在功能组件中可用
- rspec - 配置 rspec 以排除文件夹,除非它被明确指定给 rspec 运行
- react-native - React Native 嵌套平面列表(垂直平面列表中的水平平面列表)
- ms-word - 如何在 Word 中强调文本,而不改变文档,就像在 Grammarly 中一样
- c - C 编程中字符数据类型的错误处理
- sql - 更新每行中具有不同值的列
- python - 如何让python脚本无限期地运行
- python - Flask hello world 应用程序在 Spyder 或 Canopy 中不起作用
- qt - libWebSockets 上的 Qt Wrapper 类 - 不从回调方法发出信号