【问题标题】:Make Tkinter.Listbox selection persist使 Tkinter.Listbox 选择持续存在
【发布时间】:2014-01-16 23:28:11
【问题描述】:

我有一个程序,我需要从 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. 突出显示您在输入字段中输入的任何内容 => 列表框中的选择被清除。


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

【问题讨论】:

    标签: python python-2.7 listbox tkinter


    【解决方案1】:

    我知道这是一个老问题,但是当我遇到同样的问题时,这是第一个谷歌搜索结果。在使用 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])
    

    【讨论】:

    • Listbox 上使用exportselection=0 对我有用。我不明白反对票。
    【解决方案2】:

    就目前而言,我无法彻底解决这个问题。一种解决方法是创建一个变量,该变量将在单击时存储选定的列表值:

    selected = None
    def onselect(e):
        global selected
        selected = listbox.selection_get()
    
    listbox.bind('<<ListboxSelect>>', onselect)
    

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

    【讨论】:

      猜你喜欢
      • 2021-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-27
      相关资源
      最近更新 更多