【问题标题】:wxPython subclass getting attributes from classwxPython 子类从类中获取属性
【发布时间】:2012-07-31 21:39:07
【问题描述】:

我有一个 wxpython 程序,我按照教程将 wx.Dialog 子类化。在对话框中,我创建了一个面板和一个 sizer。

class StretchDialog(wx.Dialog):

'''A generic image processing dialogue which handles data IO and user interface.
This is extended for individual stretches to allow for the necessary parameters
to be defined.'''

def __init__(self, *args, **kwargs):
    super(StretchDialog, self).__init__(*args, **kwargs)

    self.InitUI()
    self.SetSize((600,700))

def InitUI(self):
    panel =  wx.Panel(self)
    sizer = wx.GridBagSizer(10,5)

块注释描述了我想要实现的功能,本质上是使用它作为基础动态生成更复杂的对话框。为此,我已经尝试过:

class LinearStretchSubClass(StretchDialog):
'''This class subclasses Stretch Dialog and extends it by adding 
    the necessary UI elements for a linear stretch'''

def InitUI(self):
    '''Inherits all of the UI items from StretchDialog.InitUI if called as a method'''
    testtext = wx.StaticText(panel, label="This is a test")
    sizer.Add(testtext, pos=(10,3))

我通过 InitUI 方法调用子类,以便能够扩展,但不会覆盖父类的 InitUI 中的 UI 生成。我无法做的是将面板和可能的 sizer 属性从父级传递给子级。

我尝试了 panel = StretchDialog.panel 和 panel = StretchDialog.InitUI.panel 的多种变体。

在 wxpython 中是否可以通过继承父类来实现这一点?如果是这样,我在尝试访问面板时如何弄乱命名空间?

【问题讨论】:

    标签: python oop wxpython


    【解决方案1】:

    您在子类中的 InitUI 导致 InitUI 不会在 StretchDialog 中被调用

    你可以这样做

    class StretchDialog(wx.Dialog):
    
        '''A generic image processing dialogue which handles data IO and user interface.
          This is extended for individual stretches to allow for the necessary parameters
          to be defined.'''
    
        def __init__(self, *args, **kwargs):
            super(StretchDialog, self).__init__(*args, **kwargs)
    
            self.InitUI()
            self.SetSize((600,700))
    
       def InitUI(self):
           #save references for later access
           self.panel =  wx.Panel(self)
           self.sizer = wx.GridBagSizer(10,5)
    

    然后在你的孩子班里

    class LinearStretchSubClass(StretchDialog):
    '''This class subclasses Stretch Dialog and extends it by adding 
    the necessary UI elements for a linear stretch'''
    
        def InitUI(self):
        '''Inherits all of the UI items from StretchDialog.InitUI if called as a method'''
             StretchDialog.InitUI(self) #call parent function
             testtext = wx.StaticText(self.panel, label="This is a test")
             self.sizer.Add(testtext, pos=(10,3))
    

    【讨论】:

    • 非常棒。我将不得不返回并重新阅读所有命名空间文档,以确保我完全掌握了变量在父子之间的传递。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-16
    • 1970-01-01
    相关资源
    最近更新 更多