Sample code usable Tkinter listbox

Alf P. Steinbach alfps at start.no
Wed Mar 3 13:51:23 EST 2010


* Alf P. Steinbach:
> In case Someone Else(TM) may need this.
> 
> This code is just how it currently looks, what I needed for my code, so 
> it's not a full-fledged or even tested class.
> 
> But it works.


That code evolved a little to cover more Tk listbox quirks (thanks to Ratingrick 
for the "activestyle"):


<code>
class UsableListbox( t.Frame ):
     def __init__( self, parent_widget ):
         t.Frame.__init__( self, parent_widget )
         scrollbar = t.Scrollbar( self, orient = "vertical" )
         self.lb = t.Listbox(
             self,
             exportselection = 0, activestyle = "none", selectmode = "browse",
             yscrollcommand = scrollbar.set
             )
         scrollbar.config( command = self.lb.yview )
         scrollbar.pack( side = "right", fill = "y" )
         self.lb.pack( side = "left", fill = "both", expand = 1 )

     def current_index( self ):
         indices = self.lb.curselection()
         assert( len( indices ) <= 1 )       # TODO: about multi-selection.
         return None if len( indices ) == 0 else int( indices[0] )

     def item_at( self, i ):
         assert( 0 <= i < self.item_count() )
         return "" if i is None else self.lb.get( i )

     def current( self ):
         #return self.lb.get( "active" )     # Incorrect with mousing
         return self.item_at( self.current_index() )

     def item_count( self ):
         return self.lb.size()

     def clear( self ):
         self.lb.delete( 0, "end" )

     def append( self, item ):
         self.lb.insert( "end", item )
         return self.item_count() - 1

     def scroll_into_view( self, i ):
         self.lb.see( i )

     def select_item( self, i ):
         assert( 0 <= i < self.item_count() )
         old_i = self.current_index();
         self.scroll_into_view( i )
         if old_i is not None and old_i == i:
             return
         self.lb.selection_set( i )
         if old_i is not None:
             self.lb.selection_clear( old_i )

     def add_selection_event_handler( self, handler ):
         "An event handler takes one argument, a Tkinter Event"
         return self.lb.bind( "<<ListboxSelect>>", handler )
</code>


Cheers,

- Alf



More information about the Python-list mailing list