如何以编程方式定义Traits / UI View的内容?

时间:2016-12-22 13:33:25

标签: python-2.7 enthought traitsui

我有一个案例,其中我不知道 HasTraits 子类的所需内容(即 Traits 的集合),直到程序运行时,因为它取决于解析具有可变内容的特定文件的结果。

如何在调用 configure_traits ()方法之前以编程方式自定义此HasTraits子类的 View

这是一个简单的测试用例,它说明了问题:

#! /usr/bin/env python

'Test case, showing problem with dynamically constructed view.'

from traits.api   import HasTraits
from traitsui.api import View, Item

class DynamicViewTester(HasTraits):
    'Tries to dynamically construct its View, using default_traits_view().'

    def default_traits_view(self):
        view = View(
            Item(label='Hello, World!'),
            title='Dynamically Assembled View',
        )
        view.add_trait('msg', Item(label='Goodbye, World.'))
        return view

if(__name__ == '__main__'):
    DynamicViewTester().configure_traits()

当我运行此代码时,我只看到“Hello,World!”生成的GUI中的消息。我没有看到“再见,世界”。消息。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案:

#! /usr/bin/env python

'Test case, showing solution to dynamically constructed view problem.'

from traits.api   import HasTraits, String
from traitsui.api import View, Item

class DynamicViewTester(HasTraits):
    'Dynamically construct its View, using default_traits_view().'

    def __init__(self, *args, **traits):
        super(DynamicViewTester, self).__init__(*args, **traits)

        # Here is where I'll parse the input file, constructing 'content' accordingly.
        content = []
        content.append(Item(label='Hello, World!'))
        content.append(Item(label='Goodbye, World.'))

        self._content = content

    def default_traits_view(self):
        view = View(
            title='Dynamically Assembled View',
            height=0.4,
            width=0.4,
        )
        view.set_content(self._content)
        return view

if(__name__ == '__main__'):
    DynamicViewTester().configure_traits()