【问题标题】:How do I define the contents of a Traits/UI View programmatically?如何以编程方式定义 Traits/UI 视图的内容?
【发布时间】:2016-12-22 13:33:24
【问题描述】:

我有一种情况,直到程序运行时我才知道 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 中的消息。我没有看到“再见,世界”。消息。

【问题讨论】:

    标签: python-2.7 enthought traitsui


    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 2011-03-28
      • 2017-06-18
      • 2012-08-22
      • 2019-08-07
      • 1970-01-01
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多