要单独使用 GetSelection(),您需要将 ComboBox 设置为只读。这是一种通过点击一个字符进行查询的好方法。使用 SetInsertionPoint 和 SetMark 将光标保持在查询的下一个字符串上。我使用了 Mike 建议的示例 •Auto-Completion In wxPython wxComboBox 并修改了我的代码以使用这些实例。因为我总是使用 boxsizers 和 open 函数,所以我需要取消 wx.EVT_TEXT 事件。以下是它的工作原理:
## copy/paste to text file
'''
73,"N WASHINGTON ST"
95,"BRIAR CREEK RD"
97,"N INDEPENDENCE AVE"
09,"N ADAMS ST"
13,"N JEFFERSON ST"
19,"N MADISON ST"
21,"QUAIL CREEK DR"
24,"INDIAN DR"
12,"CHEROKEE TRAIL"
50,"CORONADO TRAIL"
'''
import wx, os
from cStringIO import StringIO
import csv
class MainFrame(wx.Frame):
def __init__(self, parent, choices=[], style=0):
wx.Frame.__init__(self,None,wx.ID_ANY,title='test combo autocomplete',size=(225, 70))
self.vbox= wx.BoxSizer(wx.VERTICAL)
self.background = wx.Panel(self)
self.OpenDir = wx.TextCtrl(self,style=wx.PROCESS_ENTER|wx.TE_CENTRE)
self.filter = wx.ComboBox(self, wx.ID_ANY, style=wx.CB_DROPDOWN)
self.OpenDir.Bind(wx.EVT_LEFT_UP,self.OnChooseRoot)
self.filter.Bind(wx.EVT_TEXT, self.OnTextChanged)
hsizer1 = wx.BoxSizer(wx.HORIZONTAL)
hsizer1.Add(self.OpenDir,1)
hsizer2 = wx.BoxSizer(wx.HORIZONTAL)
hsizer2.Add(self.filter,1)
self.vbox.Add(hsizer1,proportion = 0,flag = wx.EXPAND)
self.vbox.Add(hsizer2,proportion = 0,flag = wx.EXPAND)
self.SetSizer(self.vbox)
self.Show()
self.OpenDir.SetValue("click to open directory")
def OnTextChanged(self, event):
def refresh():
wnd = self.filter
currentText = event.GetString()
while wnd:
print currentText
wnd.Layout()
print wnd.Layout()
wnd = wnd.GetParent()
self.filter.SetInsertionPoint(len(currentText))
self.filter.SetMark(len(currentText), len(self.choices))
self.filter.Refresh()
refresh()
event.Skip()
def OnChooseRoot(self, event):
self.dirname=""
dlg = wx.FileDialog(self, "choose a file to open", self.dirname,
"", "*.*", wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
self.pathname = dlg.GetPath()
self.f = open(os.path.join(self.dirname, self.filename), 'r')
self.text = self.f.read()
labeltop = self.dirname + '\\'
self.OpenDir.SetValue(labeltop + self.filename)
sources = [StringIO(self.text)]
for i, source in enumerate(sources):
c = list(csv.reader(source))
self.choices = [x[1] for x in c]
self.filter.SetItems(self.choices)
app = wx.App(redirect=False)
frame = MainFrame(None)
app.MainLoop()