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

wx ListBox控件FindString方法无法正常工作,求排查原因

wxListBox.FindString 始终返回-1的问题解决

我已成功将字典art中的值加载到wxListBox控件,但调用self.list_box_1.FindString('ray', True)始终返回-1。尝试过开关大小写敏感、切换单双引号、匹配完整/部分内容等操作,均无效果且未报错,最终自行实现了checkname函数完成开头匹配的查找需求。

加载列表的代码

art = {'A1':'Horace Silver', 'A2':'Murray Perahia', 'A3':'Kieth Jarret',
       'A4':'Andras Schiff', 'A5':'Tord Gustavsen Trio'}
art = dict(sorted(art.items(), key=lambda item: item[1]))
self.list_box_1.InsertItems(list(art.values()),0)
print(self.list_box_1.FindString('ray', True))  # 始终输出-1

自定义查找函数

def checkname(self,l,n):
    for i in range(l.GetCount()):
        name = l.GetString(i)
        x = name.find(n,0)
        if x > -1:
            return [i, name]

其中l为ListBox实例,n为待查找字符串。


问题原因

wxListBox的FindString方法默认开启精确匹配(第三个参数exactMatch默认值为True),只有当列表项与目标字符串完全一致时才会返回索引。你传入的'ray'在列表中没有完全匹配的项,因此无论大小写敏感设置如何,都会返回-1。

解决方案

  1. 前缀匹配(内置方法)
    如果需要前缀匹配,可显式将exactMatch设为False,此时会匹配以目标字符串开头的列表项:

    # 大小写不敏感的前缀匹配
    index = self.list_box_1.FindString('Hor', False, False)
    print(index)  # 会返回Horace Silver对应的索引
    
  2. 包含匹配(自定义函数)
    若要实现任意位置的子串匹配,内置方法无法直接完成,你的checkname函数是可行方案。可优化为支持大小写不敏感、返回所有匹配项:

    def checkname(self, list_box, target, case_sensitive=True):
        matches = []
        for idx in range(list_box.GetCount()):
            item = list_box.GetString(idx)
            if case_sensitive:
                if target in item:
                    matches.append((idx, item))
            else:
                if target.lower() in item.lower():
                    matches.append((idx, item))
        return matches if matches else None
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 14:37:51