使Tkinter.Listbox选择保持不变

时间:2013-12-30 04:40:34

标签: python python-2.7 listbox tkinter

我有一个程序,我需要从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()

重现的步骤:

  1. 在输入字段中输入内容。

  2. 在列表框中选择一些内容。

  3. 突出显示您在输入字段中输入的内容=>列表框中的选择被清除。


  4. 这个与类似问题How to select at the same time from two Listbox?相关的问题建议使用exportselection=0,这对我来说似乎不起作用。在这种情况下,selection = listbox.selection_get()会在右侧线条仍然突出显示时抛出错误。

2 个答案:

答案 0 :(得分:0)

至于现在,我无法彻底克服这个问题。一种方法是创建一个变量,它将在点击时存储选定的列表值:

selected = None
def onselect(e):
    global selected
    selected = listbox.selection_get()

listbox.bind('<<ListboxSelect>>', onselect)

这不会保留突出显示,但选择现在存储在变量中,可以进一步使用。

答案 1 :(得分:-1)

我知道这是一个老问题,但这是我遇到相同问题时的第一个Google搜索结果。我在使用selection_get()时看到使用2个列表框的奇怪行为,以及选择持久性问题。

selection_get()是Tkinter中的通用窗口小部件方法,它返回的是最后在其他窗口小部件中所做的选择,从而产生了一些非常奇怪的行为。相反,可以使用ListBox方法curselection()来将选定的索引作为元组返回,然后可以使用ListBox的get(index)方法来获取值。

要解决持久性问题,请在实例化ListBox实例时设置exportselection=0

list_box = tk.Listbox(master, exportselection=False)

...

selected_indices = list_box.curselection()
first_selected_value = list_box.get(selected_indices[0])