In my wxpython program, my panel is behaving differently depending on whether I make it a derived class or a straight panel instance:
import wx class PanelWithText(wx.Panel): def __init__(self, parent): super(PanelWithText, self).__init__(parent) hbox1 = wx.BoxSizer(wx.HORIZONTAL) panel1 = wx.Panel(parent) st1 = wx.StaticText(panel1, label='Some Text') hbox1.Add(st1) class Example(wx.Frame): def __init__(self, parent, title): super(Example, self).__init__(parent, title=title, size=(390, 350)) panel = wx.Panel(self) vbox = wx.BoxSizer(wx.VERTICAL) hbox1 = wx.BoxSizer(wx.HORIZONTAL) # comment out from here panel1 = wx.Panel(panel) # st1 = wx.StaticText(panel1, label='Some Text') # hbox1.Add(st1) # to here # panel1 = PanelWithText(panel) vbox.Add(panel1) panel.SetSizer(vbox) self.Centre() self.Show() if __name__ == '__main__': app = wx.App() Example(None, title='Example') app.MainLoop()
If I run it as is, it looks fine. If I run it commenting out the four lines that create panel1 and uncommenting the line that creates panel1 using the derived class, the "Some Text" gets clipped and only shows "Sor". Worse things start happening when I make a non-trivial program.
These two seem identical to me. What is the difference?
I'm using: Python 2.7.6 wxpython 3.0.0.0 Mac Yosemite 10.10.2
The problem is in the parenting. The problem is that in the first example you have the StaticText
widget's parent set correctly to panel1
. In your PanelWithText
class, you set its parent to the top level panel instead of the panel class, which is incorrect. Here is a fixed example:
import wx
class PanelWithText(wx.Panel):
def __init__(self, parent):
super(PanelWithText, self).__init__(parent)
hbox1 = wx.BoxSizer(wx.HORIZONTAL)
st1 = wx.StaticText(self, label='Some Text')
hbox1.Add(st1)
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title=title,
size=(390, 350))
panel = wx.Panel(self)
vbox = wx.BoxSizer(wx.VERTICAL)
#hbox1 = wx.BoxSizer(wx.HORIZONTAL) # comment out from here
#panel1 = wx.Panel(panel) #
#st1 = wx.StaticText(panel1, label='Some Text') #
#hbox1.Add(st1) # to here
panel1 = PanelWithText(panel)
vbox.Add(panel1)
panel.SetSizer(vbox)
self.Centre()
self.Show()
if __name__ == '__main__':
import wx.lib.mixins.inspection
app = wx.App()
Example(None, title='Example')
wx.lib.inspection.InspectionTool().Show()
app.MainLoop()