python - 使 Tkinter.Listbox 选择持久化

标签 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()

重现步骤:
  • 在输入字段中输入一些内容。
  • 在列表框中选择某些内容。
  • 突出显示您在输入字段中输入的任何内容 => 列表框中的选择将被清除。


  • 此相关问题与类似问题 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/

    相关文章:

    python - 为什么在顶层按住 'X' 按钮会停止执行 tkinter 中的主窗口?

    python - 将丑陋的 csv 解析为 Pandas DataFrame 的最佳方法

    python - pip install lxml centOSFailed building wheel for lxml

    c# - 更改项目的显示方式 WPF 列表框

    python - 将给定行移动到 DataFrame 的末尾

    Python - map() 拆分并仅获取第一部分

    python - python-config 可能存在 BUG?!使用 --ldflags 时它不会打印完整路径

    python - 子进程登录到远程主机而不是在 python 中出现

    c# - 为什么我的 WPF 绑定(bind)不起作用?

    c# - Winforms:如何创建具有可变项目高度的列表框