wxPython comboBox实现自动提示功能

最近在使用python做一个桌面应用,使用到了ComboBox这个控件,但是对于这个控件的想法是能够实现类似于百度搜索框的功能,输入相应的搜索内容,能够显示下拉列表,下拉列表中显示相关的提示信息。


#! /usr/bin/env python3


import wx

class SearchComboBox(wx.ComboBox):
    def __init__(self, parent, choices,style):
        super(SearchComboBox, self).__init__(parent = parent, choices = choices, style = style)
        self.choices = choices
        self.initUI()
    
    def initUI(self):
        self.ignoreEvtText = False
        self.Bind(wx.EVT_TEXT, self.textChange)
    
    def textChange(self, event):
        if self.ignoreEvtText:
            return
        currentText = event.GetString()
        #这里先判断内容是否为空,如果为空的话,需要让下拉菜单隐藏起来
        if currentText=='':
            self.SetItems(self.choices)
            self.Dismiss()
        
        
        currentText = event.GetString()
        found = False
        choiceTemp = []
        for path in self.choices:
            if currentText.lower() in path.lower():
                found = True
                choiceTemp.append(path)
    
        if found:
            self.ignoreEvtText = True
            self.SetItems(choiceTemp)
            self.Popup()
            self.SetValue(currentText)
            self.SetInsertionPoint(len(currentText))
            self.ignoreEvtText = False
        if not found:
            self.Dismiss()
            self.SetInsertionPoint(len(currentText))
            event.Skip()

重设数据源self.SetItems过后文本框也会被清空,所以self.SetValue(currentText)将文本重新设置回去,但是会遇到递归死掉的问题,没找到其他解决方式,使用 ignoreEvtText标志规避了无限递归的问题

USE

pathCache = ["awd","fegseg","grgr"] 
self.path_text = XKSearchCombo.SearchComboBox(panel,choices = pathsCache,style = wx.CB_DROPDOWN)
self.path_text.SetValue("")
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容