473,785 Members | 2,275 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

autocomplete

hello.
I have been working all too hard trying to figure out how to get
TextCtrlAutoCom plete.py to start another word after it finishes the
last word. I want it to start the autocomplete process all over again
after it finishes the autocomplete process. I have striped down the
program to a smaller version than the orginal. it now works in a
multiline wx.textctrl box. belive that the program only needs one or
two lines to complete the taks and start all over again.

here is a copy of the code
'''

wxPython Custom Widget Collection 20060207
Written By: Edward Flick ()
Michele Petrazzo (michele -=dot=- petrazzo -=at=- unipex
-=dot=- it)
Will Sadkin (wsadkin-=at=- nameconnector -=dot=- com)
Copyright 2006 (c) CDF Inc. ( http://www.cdf-imaging.com )
Contributed to the wxPython project under the wxPython project's
license.

'''

import wx
import sys

import wx.lib.mixins.l istctrl as listmix
class myListCtrl(wx.L istCtrl, listmix.ListCtr lAutoWidthMixin ):
def __init__(self,
parent,
ID=-1,
pos=wx.DefaultP osition,
size=wx.Default Size,
style=0):
wx.ListCtrl.__i nit__(self, parent, ID, pos, size, style)
listmix.ListCtr lAutoWidthMixin .__init__(self)

class TextCtrlAutoCom plete (wx.TextCtrl, listmix.ColumnS orterMixin ):

def __init__ ( self, parent, choices = None,
showHead=False, dropDownClick=T rue,
colFetch=-1, colSearch=0, hideOnNoMatch=T rue,
selectCallback= None, entryCallback=N one,
matchFunction=N one,
**therest) :
'''
Constructor works just like wx.TextCtrl except you can pass in
a
list of choices. You can also change the choice list at any
time
by calling setChoices.
'''

if therest.has_key ('style'):
therest['style']=wx.TE_PROCESS_ ENTER | therest['style']
else:
therest['style']=wx.TE_PROCESS_ ENTER
wx.TextCtrl.__i nit__(self,pare nt,-1,'',size=(500, 500),style=wx.T E_MULTILINE)
#wx.TextCtrl.__ init__(self, parent, **therest )
self._hideOnNoM atch = hideOnNoMatch
self._selectCal lback = selectCallback
self._matchFunc tion = matchFunction
self._screenhei ght = wx.SystemSettin gs.GetMetric(
wx.SYS_SCREEN_Y )

#sort variable needed by listmix
self.itemDataMa p = dict()

#widgets
self.dropdown = wx.PopupWindow( self )

#Control the style
flags = wx.LC_REPORT | wx.LC_SINGLE_SE L | wx.LC_SORT_ASCE NDING
if not (showHead) :
flags = flags | wx.LC_NO_HEADER

#Create the list and bind the events
self.dropdownli stbox = myListCtrl( self.dropdown, style=flags,
pos=wx.Point( 0, 0) )
gp = self
while ( gp != None ) :
gp = gp.GetParent()
self.Bind( wx.EVT_TEXT , self.onEnteredT ext, self )
self.Bind( wx.EVT_KEY_DOWN , self.onKeyDown, self )
self.dropdownli stbox.Bind(wx.E VT_LEFT_DCLICK,
self.onListDCli ck)

def onListDClick(se lf, evt):
self._setValueF romSelected()

def onEnteredText(s elf, event):
text = event.GetString ()
#print('onEnter dText text: ',text)
if self._entryCall back:
self._entryCall back()
if not text:
# control is empty; hide dropdown if shown:
if self.dropdown.I sShown():
self._showDropD own(False)
event.Skip()
return
found = False
choices = self._choices

for numCh, choice in enumerate(choic es):
if self._matchFunc tion and self._matchFunc tion(text,
choice):
found = True
elif choice.lower(). startswith(text .lower()) :
found = True
if found:
self._showDropD own(True)
item = self.dropdownli stbox.GetItem(n umCh)
toSel = item.GetId()
self.dropdownli stbox.Select(to Sel)
break

if not found:

self.dropdownli stbox.Select(se lf.dropdownlist box.GetFirstSel ected(),
False)
if self._hideOnNoM atch:
self._showDropD own(False)

self._listItemV isible()

event.Skip ()

def onKeyDown ( self, event ) :
""" Do some work when the user press on the keys:
up and down: move the cursor
left and right: move the search
"""
skip = True

sel = self.dropdownli stbox.GetFirstS elected()
visible = self.dropdown.I sShown()

KC = event.GetKeyCod e()
if KC == wx.WXK_DOWN :
if sel < (self.dropdownl istbox.GetItemC ount () - 1) :
self.dropdownli stbox.Select ( sel+1 )
self._listItemV isible()
self._showDropD own ()
skip = False
elif KC == wx.WXK_UP :
if sel > 0 :
self.dropdownli stbox.Select ( sel - 1 )
self._listItemV isible()
self._showDropD own ()
skip = False

if visible :
if event.GetKeyCod e() == wx.WXK_RETURN :
self._setValueF romSelected()
skip = False
if event.GetKeyCod e() == wx.WXK_ESCAPE :
self._showDropD own( False )
skip = False
if skip :
event.Skip()

def onListItemSelec ted (self, event):
self._setValueF romSelected()
event.Skip()

def onClickToggleDo wn(self, event):
self._lastinser tionpoint = self.GetInserti onPoint()
event.Skip ()

def onClickToggleUp ( self, event ) :
if ( self.GetInserti onPoint() == self._lastinser tionpoint ) :
self._showDropD own ( not self.dropdown.I sShown() )
event.Skip ()
# -- Interfaces methods

def SetChoices(self , choices):

#Sets the choices available in the popup wx.ListBox.
#The items will be sorted case insensitively.
self._choices = choices
flags = wx.LC_REPORT | wx.LC_SINGLE_SE L | wx.LC_SORT_ASCE NDING
| wx.LC_NO_HEADER
self._updateDat aList(self._cho ices)
self.dropdownli stbox.InsertCol umn(0, "")
for num, colVal in enumerate(self. _choices):
index =
self.dropdownli stbox.InsertIma geStringItem(sy s.maxint, colVal, -1)
self.dropdownli stbox.SetString Item(index, 0, colVal)
self.dropdownli stbox.SetItemDa ta(index, num)

self._setListSi ze()

# there is only one choice for both search and fetch if setting
a single column:
self._colSearch = 0
self._colFetch = -1
def SetSelectCallba ck(self, cb=None):
self._selectCal lback = cb

def SetEntryCallbac k(self, cb=None):
self._entryCall back = cb

#-- Internal methods
def _setValueFromSe lected( self ) :
'''
Sets the wx.TextCtrl value from the selected wx.ListCtrl item.
Will do nothing if no item is selected in the wx.ListCtrl.
'''
sel = self.dropdownli stbox.GetFirstS elected()
if sel > -1:
if self._colFetch != -1: col = self._colFetch
else: col = self._colSearch
itemtext = self.dropdownli stbox.GetItem(s el, col).GetText()

if self._selectCal lback:
dd = self.dropdownli stbox
values = [dd.GetItem(sel, x).GetText()
for x in xrange(dd.GetCo lumnCount())]
self._selectCal lback( values )
self.SetValue (itemtext)
self.SetInserti onPointEnd ()
self.SetSelecti on ( -1, -1 )
self._showDropD own ( False )

def _showDropDown ( self, show = True ) :
'''
Either display the drop down list (show = True) or hide it
(show = False).
'''

if show :
size = self.dropdown.G etSize()
width, height = self . GetSizeTuple()
x, y = self . ClientToScreenX Y ( wx.CentreX+6, wx.CentreY+6
)
if size.GetWidth() != width :
size.SetWidth(w idth)
self.dropdown.S etSize(size)

self.dropdownli stbox.SetSize(s elf.dropdown.Ge tClientSize())
if (y + size.GetHeight( )) < self._screenhei ght :
self.dropdown . SetPosition ( wx.Point(x, y) )
else:
self.dropdown . SetPosition ( wx.Point(x, y - height -
size.GetHeight( )) )
self.dropdown.S how ( show )

def _listItemVisibl e( self ) :
'''
Moves the selected item to the top of the list ensuring it is
always visible.
'''
toSel = self.dropdownli stbox.GetFirstS elected ()
if toSel == -1: return
self.dropdownli stbox.EnsureVis ible( toSel )

def _updateDataList (self, choices):
#delete, if need, all the previous data
if self.dropdownli stbox.GetColumn Count() != 0:
self.dropdownli stbox.DeleteAll Columns()
self.dropdownli stbox.DeleteAll Items()

#and update the dict
if choices:
for numVal, data in enumerate(choic es):
self.itemDataMa p[numVal] = data
#print("data is %s",data)
else:
numVal = 0
self.SetColumnC ount(numVal)

def _setListSize(se lf):
choices = self._choices
longest = 0
for choice in choices :
longest = max(len(choice) , longest)

#longest += 3
itemcount = min( len( choices ) , 7 ) + .5
charheight = self.dropdownli stbox.GetCharHe ight()
charwidth = self.dropdownli stbox.GetCharWi dth()
self.popupsize = wx.Size( charwidth*longe st,
charheight*item count )
self.dropdownli stbox.SetSize ( self.popupsize )
self.dropdown.S etClientSize( self.popupsize )

class test:
def __init__(self):
args = dict()
args["selectCallback "] = self.selectCall back

self.dynamic_ch oices = [
'hello world', 'abandon', 'acorn', 'acute',
'adore',
'aegis', 'ascertain', 'asteroid',
'beautiful', 'bold', 'classic',
'daring', 'dazzling', 'debonair', 'definitive',
'effective', 'elegant',
'http://python.org', 'http://www.google.com' ,
'fabulous', 'fantastic', 'friendly',
'forgiving', 'feature',
'sage', 'scarlet', 'scenic', 'seaside',
'showpiece', 'spiffy',
'www.wxPython.o rg', 'www.osafoundat ion.org'
]
app = wx.PySimpleApp( )
frm = wx.Frame(None,-1,"Test",
style=wx.CLEAR
|wx.DEFAULT_FRA ME_STYLE
)
panel = wx.Panel(frm)
self._ctrl = TextCtrlAutoCom plete(panel, **args)
self.onBtDynami cChoices(self.o nBtDynamicChoic es)

frm.Show()
app.MainLoop()
def onBtDynamicChoi ces(self, event):
self._ctrl.SetC hoices(self.dyn amic_choices)
self._ctrl.SetE ntryCallback(se lf.setDynamicCh oices)
def match(self, text, choice):
t = text.lower()
c = choice.lower()
#print('The Value is %S',choice)
return c.startswith(t)

def setDynamicChoic es(self):
if wx.EVT_KEY_DOWN == ' ': print "Space bar pressed"
text = self._ctrl.GetV alue().lower()
choices = [choice for choice in self.dynamic_ch oices if
self.match(text , choice)]
self._ctrl.SetC hoices(choices)
#print('The Value is %S',text)

def selectCallback( self, values):
""" Simply function that receive the row values when the
user select an item
"""
print "Select Callback called...:", values
self.wordCheck( values)

def wordCheck(self, values):
pass #print"Word to check:",values
if __name__ == "__main__":
test()

Jun 10 '06 #1
0 2074

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5256
by: bc | last post by:
Hi, Is it possible to detect if the IE autocomplete function in a current context such as a textbox is activated (ie. dropdown with previously entered info is visible)? Problem: I use a script as a basis for binding <enter> in textbox to a button, BUT <enter> in the dropdown autocomplete generated by IE also triggers this event. The script is available below (in .NET context but the idea should
40
10903
by: Alex | last post by:
Hello, does anybody know how to turn off the autocomplete feature for a certain text field? I am aware of the "autocomplete" attribute, but I have seen other implementions achieving it without any such attribute and am wondering whether there is another way to do it .... like via CSS or a naming convention or .......
0
1293
by: Thorsten Ottosen | last post by:
Hi, I'm using the AutoComplete attribute to control transactions. What happens if I call functions with the AutoComplete attribute from within other functions with the AutoComplete attribute? For example public class Foo
8
3376
by: moondaddy | last post by:
I have a form for entering a user's address and all fields have a required validating control associated with them and the error msg for each field displays right next to it. The normal behavior is that the error msg doesn't show unit the use hits the submit button or the user enters data and moves the focus to another control so the field becomes dirty. So far so good. Now when the user goes back to that control and starts to input data...
2
4509
by: Mrinal Kamboj | last post by:
Hi , Need to get some basic info regarding AutoComplete Attribute in COM+ . I am having a class with TransactionOption set to Required , now for this class , can i mark all the methods with AutoComplete attribute , irrespective of the fact , whether i do implement Try .. Catch block or not , as some of the methods are just meant for intermediary calculation and are private , or i just need to mark one method that's public as...
1
1764
by: thubba2000 | last post by:
We have a web application developed using IBuySpy. In older versions, Autocomplete on all web forms works. In our latest version, it stopped working on all clients. I have gone through all the groups and tried a bunch of things. Two main areas I keep seeing are, 1. Browser Settings not set correctly. 2. Ability to turn off Autocomplete for a control and a form.
1
5215
by: rbg.net | last post by:
I know that there is a autocomplete property for the HTML "INPUT type=text" control which if set to OFF, disables autocomplete of the input textbox (doesn't remember previously entered values) However there is no such corresponding property for the TEXTBOX ASP.NET Webcontrol in ASP.NET 1.1. I know that there is a AutoComplete Property in the TEXTBOX ASP.NET WebControl in ASP.NET 2.0. Thus I can use AutoComplete.Disabled property in...
8
5759
by: nil | last post by:
Hello all, It's urgent... i want to add autocomplete textbox facility in my application like google. as you type it suggests option to the user..i want the same kind of facility...i know i can do only with ajax(xml and javascript) but i want to fetch possible values from database and want to show as the user types in text box.
1
3854
by: wkerplunk | last post by:
Below is what I have build with several different languages. It works great but I need help, I am stuck. When you click on an item in the dropdown autocomplete div it does a mousedown function and send the item number to the xmlHttp and works awesome. Now I need to add an apply button next to it. so they can type in the complete number then hit apply and it does the same function. I cant get it to work with the script I have. The image...
5
5334
by: Doug | last post by:
Hi I have a simple form, just with one combo box and an OK button - and i have tried to use the autocomplete routine and I have enabled autocomplete in the combo box properties. http://www.java2s.com/Code/CSharp/Components/UseanAutocompleteComboBox.htm That is the link that I copied the code from - but the box doesnt autocomplete and I dont know what i am doing wrong.
0
10162
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10101
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9959
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7509
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6744
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5528
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4063
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3665
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2893
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.