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

How do I define the contents of a Traits/UI View programmatically?

我有一个案例,我不知道 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()

当我 运行 这段代码时,我只在生成的 GUI 中看到 "Hello, World!" 消息。我没有看到 "Goodbye, World." 消息。

我找到了解决方案:

#! /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()