您的位置:首页 > 编程语言 > Python开发

wxpython comboBox 自动完成提示功能

2015-09-08 00:00 639 查看

摘要

最近在使用python做一个桌面应用,使用到了ComboBox这个控件,但是对于这个控件的想法是能够实现类似于百度搜索框的功能,输入相应的搜索内容,能够显示下拉列表,下拉列表中显示相关的提示信息。google了半天有的功能只有自动补充完成,并不能够达到显示下拉列表的形式,一旦遇到多个联想词的时候就会有些问题。所以自己研究了下,在其原先的基础上稍微修改了下代码实现了这个功能。下面来看看代码吧

正文

# -*- coding: utf-8 -*-
import wx

class PromptingComboBox(wx.ComboBox) :
def __init__(self, parent, value, choices=[], style=0, **par):
wx.ComboBox.__init__(self, parent, wx.ID_ANY, value, style=style|wx.CB_DROPDOWN, choices=choices, **par)
self.choices = choices
#分别绑定多个事件,文本内容变化,字符输入
self.Bind(wx.EVT_TEXT, self.EvtText)
self.Bind(wx.EVT_CHAR, self.EvtChar)
self.Bind(wx.EVT_COMBOBOX, self.EvtCombobox)
self.ignoreEvtText = False

def EvtCombobox(self, event):
self.ignoreEvtText = True
event.Skip()

def EvtChar(self, event):
#这里需要注意一点事,回车键如果不过滤掉的话,EvtText会类似于进入死循环,这里还不太清楚到底是为什么
if event.GetKeyCode() == 8:
self.ignoreEvtText = True
event.Skip()

def EvtText(self, event):

currentText = event.GetString()
#这里先判断内容是否为空,如果为空的话,需要让下拉菜单隐藏起来
if currentText=='':
self.SetItems(self.choices)
self.Dismiss()
if self.ignoreEvtText:
self.ignoreEvtText = False
return

currentText = event.GetString()
found = False
choiceTemp = []
for choice in self.choices :
if choice.startswith(currentText):
self.ignoreEvtText = True
found = True
choiceTemp.append(choice)
#进行文本匹配后,如果存在的话,就将combobox的内容置为匹配到的列表,再弹出下拉菜单
if found:
print choiceTemp[0]
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()

class TrialPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent, wx.ID_ANY)

choices = [u'中国', u'中文', u'中美', 'aunt', 'uncle', 'grandson', 'granddaughter']

cb = PromptingComboBox(self, "", choices, style=wx.CB_DROPDOWN)

def derivedRelatives(self, relative):
return [relative, 'step' + relative, relative + '-in-law']

if __name__ == '__main__':
app = wx.App()
frame = wx.Frame (None, -1, 'Demo PromptingComboBox Control', size=(400, 200))
TrialPanel(frame)
frame.Show()
app.MainLoop()


以上就是全部的代码了。但是每输入一次就会闪烁一下,这还是有点小问题。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: