python - enabled_when 监听外部模型对象

标签 python enthought traits traitsui

我找到了解决原始问题的方法,但我希望其他人可以解释发生了什么。我最初注意到 enabled_when 以及我想象的 visible_when 似乎也会在响应仅源自模型对象的特征事件时生效。如果事件源自某个其他对象,即使编辑器引用它,它似乎也无法正确传播。

class DirectObjectPronoun(HasTraits):
    text=Str
    typable=Bool(False)

    traits_view=View(
        Item(name='typable'),
        Item(name='text',enabled_when='typable'))

class IndirectObjectPronoun(HasTraits):
    referent=Instance(DirectObjectPronoun,())

    traits_view=View(
        Item(name='typable',object='object.referent'),
        Item(name='text',object='object.referent',
            enabled_when='object.referent.typable'))

IndirectObjectPronoun().configure_traits()

期望的行为是当typable为True时启用文本窗口,否则禁用。观察到的行为是文本窗口始终处于禁用状态(尽管如果 typable 的默认值设置为 True,则它始终处于启用状态,因此问题必定出在监听器中。)

如果直接编辑DirectObjectPronoun,则禁用将按预期工作。

我找到了一个我不明白的解决方法。

class IndirectObjectPronoun(HasTraits):
    stupid_listener=Bool
    referent=Instance(DirectObjectPronoun,())

    traits_view=View(
        Item(name='typable',object='object.referent'),
        Item(name='text',object='object.referent',
            enabled_when='object.referent.typable'))

    @on_trait_change('referent.typable')
    def _stupid_listener_listens_stupidly(self):
        self.stupid_listener=self.referent.typable

这个想法非常简单:创建一个愚蠢的变量,除了监听条件之外什么都不做,然后将该局部变量设置为条件。

但是,当我测试这个时,我忘记更改 enabled_when 但它仍然可以正常工作。在某种程度上,添加此监听器似乎提醒了 IndirectObjectPronoun 它无论如何都应该监听此变量。看来 _stupid_listener_listens_stupidly 函数的内容很重要 - 如果您将其更改为 passprint 56 或其他内容,它就不再起作用.

有人知道这是怎么回事吗?

最佳答案

不研究源码,我不知道为什么它不起作用;至少,您所描述的不一致似乎是错误的。

更直观的解决方法/解决方案是使用委托(delegate):

class IndirectObjectPronoun(HasTraits):
    referent=Instance(DirectObjectPronoun,())
    typable = DelegatesTo('referent')

    traits_view=View(
        Item(name='typable',object='object.referent'),
        Item(name='text',object='object.referent',
             enabled_when='typable'))

关于python - enabled_when 监听外部模型对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20409629/

相关文章:

python - 我该如何处理这个回溯名称错误?这是我的第一个脚本

python - 使用 matplotlib.widgets 中的 slider 后如何获取条形图值?

rust - 将相同变量绑定(bind)到共享特征的不同类型的模式

python - Enthought Canopy 中的 IPython 缓冲区和分页

mysql - 将 Canopy 连接到 mysql

泛型错误 : expected type parameter, 找到结构

scala - 如何与 Akka Actor 一起使用可堆叠特征模式?

python - 将两种模式与 Python 中的命名捕获组结合起来?

python - 使用 concurrent.futures 一次消耗许多出队消息

python - 更改 Enthought TraitsUI TextEditor 中的字体