最近在使用python做一個(gè)桌面應(yīng)用,使用到了ComboBox這個(gè)控件,但是對(duì)于這個(gè)控件的想法是能夠?qū)崿F(xiàn)類(lèi)似于百度搜索框的功能,輸入相應(yīng)的搜索內(nèi)容霜定,能夠顯示下拉列表,下拉列表中顯示相關(guān)的提示信息捆探。
#! /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()
#這里先判斷內(nèi)容是否為空然爆,如果為空的話站粟,需要讓下拉菜單隱藏起來(lái)
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()
重設(shè)數(shù)據(jù)源self.SetItems
過(guò)后文本框也會(huì)被清空黍图,所以self.SetValue(currentText)
將文本重新設(shè)置回去,但是會(huì)遇到遞歸死掉的問(wèn)題奴烙,沒(méi)找到其他解決方式助被,使用 ignoreEvtText標(biāo)志規(guī)避了無(wú)限遞歸的問(wèn)題
USE
pathCache = ["awd","fegseg","grgr"]
self.path_text = XKSearchCombo.SearchComboBox(panel,choices = pathsCache,style = wx.CB_DROPDOWN)
self.path_text.SetValue("")
image.png