Search code examples
pythontraitsenthoughttraitsui

python Traits: Column of Buttons in Table


I would like to add a Button to the end of every line in a table.

The following code results in an PyDeadObjectError when closing the window:

from traits.api import HasTraits,Str,Int,Button,Instance
from traitsui.api import TableEditor,ObjectColumn,View
class Person(HasTraits):
    name=Str
    age=Int
    Plot_size=Button(label='Plot size')

class Display(HasTraits):
    table=List(Instance(Person))
    table_editor=TableEditor(columns=[ObjectColumn(name='name'),
        ObjectColumn(name='age'),
        ObjectColumn(name='Plot_size')],
        deletable = True,
        sortable = False,
        sort_model = False,
        show_lines = True,
        orientation = 'vertical',
        show_column_labels = True)
    traits_view=View(Item('table',editor=table_editor),resizable=True)

a=Display()
a.table.append(Person(name='Joe',age=21))
a.table.append(Person(name='John',age=27))
a.table.append(Person(name='Jenny',age=23))
a.configure_traits()

Has someone already tried to do the same? How can I get rid of this error? Is it possible to display the Button even without clicking on the corresponding cell?


Solution

  • I'm not sure what the issue is there but there is perhaps a workaround. Instead of having a column full of buttons, have one button and then use the selected row.

    from traits.api import HasTraits,Str,Int,Button,Instance, List
    from traitsui.api import TableEditor,ObjectColumn,View, Item
    
    class Person(HasTraits):
        name=Str
        age=Int
        #Plot_size=Button(label='Plot size')
    
    
    class Display(HasTraits):
        Plot_size=Button(label='Plot size')
        selected_person = Instance(Person)
    
        people=List(Instance(Person))
        table_editor=TableEditor(columns=[ObjectColumn(name='name'),
            ObjectColumn(name='age')],
            selected='selected_person',
            #ObjectColumn(name='Plot_size', editable=False)],
            deletable = True,
            sortable = False,
            sort_model = False,
            show_lines = True,
            orientation = 'vertical',
            show_column_labels = True)
    
        traits_view=View(Item('people',editor=table_editor),
                Item('Plot_size'),
                resizable=True)
    
        def _Plot_size_fired(self):
                print self.selected_person.name
    
    demo=Display(people = [Person(name='Joe',age=21),
        Person(name='John',age=27),
        Person(name='Jenny',age=23)])
    
    if __name__ == '__main__':
        demo.configure_traits()
    

    Otherwise, maybe the checkbox_column example is a good place to start.