vendredi 5 août 2016

PyhtonMegaWidget (Pmw) StrictComboBox

Dans l'article "PythonMegaWidget (Pmw) ComboBox restreind à une liste de valeur" j'expliquais comment avoir configuré une combobox pour n'accepter qu'une liste finie de valeur.

Ce hack est maintenant transformé en classe StrictComboBox .

In the previous article "PythonMegaWidget (Pmw) ComboBox restreind à une liste de valeur" I did explain how to restrict the selected value to a given list of values.
That hack has been converted to the StrictComboBox  class.

class StrictComboBox( Pmw.ComboBox ):
    """ Pmw.ComboBox that strictly restrict the selection to the list of items stored in the "items" keyword
        
        Thank to RL_ScrolledText class for their wonderfull example
        http://www.reportlab.com/examples/frml/old/rlextra/src/rlextra/graphics/guiedit/guidialogs.py                
    """
    _items = None # List of combobox items

    def __init__( self, *args, **kw ):
        # Take a local copy of some property
        for a in ['items']:
            print( a )
            if a in list(kw.keys()):
                print( ' --removed')
                v=kw[a]
                del kw[a]
            else:
                v=None
            setattr(self,a,v)

        # add the items to combobox + validator
        kw['scrolledlist_items'] = self.items
        kw['entryfield_extravalidators'] = { 'strictselect' : (self.strictselect_validate, self.strictselect_stringtovalue) }
        kw['entryfield_validate'] = { 'validator' : 'strictselect' }

        Pmw.ComboBox.__init__( *(self,)+args, **kw )
        w = self._entryfield = self.component('entryfield')

        self.initialiseoptions(StrictComboBox)
    
    def destroy(self):
        Pmw.ComboBox.destroy( self )
        

    def strictselect_validate(self, avalue):
        """ called by ComboBox entry field to validate the keyIn value """
        print( 'validate: %s' % avalue )
        if avalue in self.items:
            return Pmw.OK
        elif any( [avalue in v for v in self.items] ):
            return Pmw.PARTIAL
        else:
            return Pmw.ERROR

    def strictselect_stringtovalue(self, avalue):
        """ Not called since we did not defined min and max values """
        return None

Qui s'utilise comme ceci:
And you can use it like that:

    # StrictComboBox
    f = Frame( fbody  )
    l = Label( f, text="Prefered Parent", anchor=W, width=15 ).pack( side=LEFT, expand=N )
    combobox4 = StrictComboBox( f, items=['Dady','Mom','Sister','Grandpa'],
                        labelpos='wn', listbox_width=24, dropdown=1, # selectioncommand=choseEntry,
                        entry_state = 'disabled', entry_bg='white', entry_fg='black' )
    combobox4.pack( side=LEFT, expand=N )
    fields.append( (combobox4, None) ) # the Field and the string variable
    f.pack( side=TOP, expand=N, fill=X )

Aucun commentaire: