在 xrc 创建的对话框中替换小部件

Replacing widgets in a xrc created dialog

我想动态替换对话框的对象,但没有找到方法。该对话框是在 xrc 定义文件的帮助下创建的。

我发现的所有内容是https://www.blog.pythonlibrary.org/2012/05/05/wxpython-adding-and-removing-widgets-dynamically/:需要访问一个sizer,但据我所知,xrc 不提供对sizer 对象的访问。

有人可以帮忙吗?

我的系统:python2.7,wxpython3.0.2.0,win7

此致 洪巴兰

在 Goyo 的 post 帮助下,我找到了以下解决方案:

def exchange_control( self, control, coded ) :
"""
Exchanges a wx.TextCtrl (where wx.TE_PASSWORD is set) with a wx.TextCtrl (where
wx.TE_PASSWORD is not set) and vice versa. A similar code could be used to exchange
for exampe a DirPickerCtrl with a FilePickerCtrl.

:param wx.TextCtrl control: Contains a coded or encoded text dependend on `coded`.
:param bool coded: True if the text in `control` is coded, False if it is encoded.

:returns: 
    A new wx.TextCtrl with the coded (`coded` was False) or encoded Text (`coded` was 
    True) of `control`.
:rtype: wx.TextCtrl
"""
    containing_sizer = control.GetContainingSizer() # get the sizer containing `control`

    # Compute arguments for a new TextCtrl. 
    # - The value of style is arbitrary except the TE_PASSWORD part. 
    # - a_validator is a validator checking correctness of the value of `control`, is 
    #   optional.
    kwargs = { 'parent'   : control.Parent,
               'id'       : wx.ID_ANY,
               'value'    : control.GetValue(),
               'size'     : control.Size,
               'style'    : wx.TE_NO_VSCROLL|wx.TE_PASSWORD if coded  else wx.TE_NO_VSCROLL,
               'name'     : control.Name,
               'validator': a_validator
             }

    # Setup a new TextCtrl with the arguments kwargs
    new_text_ctrl = wx.TextCtrl( **kwargs )

    containing_sizer.Replace( control, new_text_ctrl )
    containing_sizer.Layout()

    return new_text_ctrl

# In the calling code:
# The returned `the_text_ctrl` is the TextCtrl Field with the (en)coded Text and `coded` 
# is  the boolean value  which shows if the text whithin this field is coded or encoded. 
the_text_ctrl = self.exchange_control( the_text_ctrl, coded )

编辑:

我更改了代码,因为我发现方法 Replace() 比我的第一次尝试更容易使用。