
[英]Tkinter Listbox : Botton delete the selected Items from the Listbox and JSON files
[英]Make Some Tkinter Listbox Items Always Selected
我有一个tkinter列表框,其中的列表框中的某些项目需要始终处于选中状态。 在我的应用程序中,用户需要这些项目,而列表框中的其他一些项目是可选的(应该是可选/取消选择)。
大多数示例使用'<<ListboxSelect>>'
绑定函数。
我不明白的是,如何获得用户从bind事件中选择的确切单个项目?
在我的示例代码中,最初选择的是apples
, peaches
, lettuce
。 假设我点击了apples
。 通常,此事件会取消选择apples
但是我希望我的函数运行并在apples
上设置选择,因此它看起来像是无法取消选择的。
import tkinter as tk
root = tk.Tk()
requiredlb = tk.Listbox(root, exportselection=False, activestyle='none', selectmode=tk.MULTIPLE)
for i,item in enumerate(['apples', 'oranges', 'peaches', 'carrots', 'lettuce', 'grapes']):
requiredlb.insert(tk.END, item)
if i % 2 == 0:
requiredlb.selection_set(i)
requiredlb.grid(row=6, column=1, sticky='ew')
def always_selected(event):
widget = event.widget
## What Goes Here? ##
requiredlb.bind('<<ListboxSelect>>', func=always_selected)
root.mainloop()
好,很好的问题。 这是我设法提出的解决方法,它似乎有效。
首先,创建要始终保持选中状态的索引列表:
items = ['apples', 'oranges', 'peaches', 'carrots', 'lettuce', 'grapes']
special_items = [0, 2, 4]
for i,item in enumerate(items):
...
如您所见,我对您的代码做了一些修改
然后,在事件函数中,始终要确保通过明确选择索引来选择这些索引:
def always_selected(event):
widget = event.widget
for idx in special_items:
widget.selection_set(idx)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.