我有一个程序,我需要从 Tkinter.Listbox 和一个输入字段中进行选择,然后对这些数据做一些事情。但是,如果我突出显示输入字段中的任何文本(即删除以前的条目),则列表框选择将被清除。我怎样才能克服它以便列表框选择仍然存在?
import Tkinter as tk
master = tk.Tk()
listbox = tk.Listbox(master)
listbox.grid(row=0, column=0)
items = ['a', 'b', 'c']
for item in items:
listbox.insert(tk.END, item)
efield = tk.Entry(master)
efield.grid(row=1, column=0)
tk.mainloop()
重现步骤:
此相关问题与类似问题 How to select at the same time from two Listbox?建议使用
exportselection=0
,这似乎对我不起作用。在这种情况下 selection = listbox.selection_get()
当右侧的行仍然突出显示时抛出错误。
最佳答案
我知道这是一个老问题,但是当我遇到同样的问题时,这是第一个谷歌搜索结果。使用 selection_get()
时,我看到使用 2 个列表框的奇怪行为以及选择持久性问题。selection_get()
是 Tkinter 中的通用小部件方法,它返回上次在其他小部件中进行的选择,导致一些非常奇怪的行为。相反,使用 ListBox 方法 curselection()
它将所选索引作为元组返回,然后您可以使用 ListBox 的 get(index)
如果需要,方法来获取值。
解决持久化问题,设置exportselection=0
实例化 ListBox 实例时。
list_box = tk.Listbox(master, exportselection=False)
...
selected_indices = list_box.curselection()
first_selected_value = list_box.get(selected_indices[0])
关于python - 使 Tkinter.Listbox 选择持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20833428/