You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PySimpleGUI ListBox重复点击同一项取消选中实现问询

解决PySimpleGUI ListBox重复点击取消选中的问题

实现思路

在extended选择模式下,ListBox默认不支持点击已选中项取消选中,所以需要手动维护选中状态,通过对比每次点击的项与上次选中项,判断是否触发取消操作。

具体代码实现

初始化ListBox保留原有配置,在事件循环中处理list_box的触发事件:

import PySimpleGUI as sg

# 构建窗口布局
layout = [
    [sg.Listbox(values=["项1", "项2", "项3", "项4"], select_mode="extended", key="list_box", size=(40, 25), enable_events=True)]
]

window = sg.Window("ListBox示例", layout)
last_selected_indices = []  # 存储上次选中项的索引

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    if event == "list_box":
        current_selected_items = values["list_box"]
        # 转换当前选中项为对应的索引列表
        current_indices = [window["list_box"].get_list_values().index(item) for item in current_selected_items]
        # 判断是否为重复点击同一单项
        if len(current_indices) == 1 and current_indices == last_selected_indices:
            # 清空选中状态
            window["list_box"].update(set_to_index=[])
            last_selected_indices = []
        else:
            last_selected_indices = current_indices.copy()

window.close()

代码说明

  • 用last_selected_indices变量记录上次选中项的索引
  • 每次list_box事件触发时,获取当前选中项对应的索引
  • 若当前仅选中单个项,且该索引与上次记录的一致,则调用update(set_to_index=[])清空选中状态,同时重置记录变量
  • 其他情况则更新记录变量为当前选中的索引

通过这个逻辑,就能实现点击同一列表项两次时取消选中的需求,逻辑简洁直接,无需复杂的状态管理。

内容的提问来源于stack exchange,提问作者goldberg paz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:03:20