2012-09-19 108 views
0

如何在另一個wx.Panel中放置一個wx.Panel?只是一個小的測試程序,它不工作:如何將面板放置在另一個面板中?

import wx 

class TstApp(wx.App): 
    def OnInit(self): 
     self.frame = wx.Frame(None, -1, "TstApp", wx.DefaultPosition, 
     wx.DefaultSize) 

     self.pn = wx.Panel(self.frame, -1) 
     self.pn2 = wx.Panel(self.pn, -1) 
     self.btn = wx.Button(self.pn2, -1, "A Button") 

     self.frame.Show() 
     self.SetTopWindow(self.frame) 

     return True 

app = TstApp(0) 
app.MainLoop() 

回答

0

正如菲尼亞斯已經說過,你應該只使用分級機來安排你的小部件。但如果你真的想把多個面板放在一起,那麼你也可以使用sizer。

import random 
import wx 

######################################################################## 
class RandomPanel(wx.Panel): 
    """""" 

    #---------------------------------------------------------------------- 
    def __init__(self, parent): 
     """Constructor""" 
     wx.Panel.__init__(self, parent) 
     color = random.choice(["green", "blue", "yellow", "red"]) 
     self.SetBackgroundColour(color) 

######################################################################## 
class MainPanel(wx.Panel): 
    """""" 

    #---------------------------------------------------------------------- 
    def __init__(self, parent): 
     """Constructor""" 
     wx.Panel.__init__(self, parent) 

     firstSubPanel = RandomPanel(self) 
     secondSubPanel = RandomPanel(self) 

     sizer = wx.BoxSizer(wx.VERTICAL) 
     sizer.Add(firstSubPanel, 1, wx.EXPAND|wx.ALL, 5) 
     sizer.Add(secondSubPanel, 1, wx.EXPAND|wx.ALL, 5) 
     self.SetSizer(sizer) 

######################################################################## 
class MainFrame(wx.Frame): 
    """""" 

    #---------------------------------------------------------------------- 
    def __init__(self): 
     """Constructor""" 
     wx.Frame.__init__(self, None, title="Panels") 

     panel = MainPanel(self) 


if __name__ == "__main__": 
    app = wx.App(False) 
    frame = MainFrame() 
    frame.Show() 
    app.MainLoop() 
0

你完全錯過了主題爲「佈局管理我建議你閱讀本教程的layout section上zetcode我介紹wx.BoxSizer s到解決您的例子。代碼:

import wx 

class TstApp(wx.App): 
    def OnInit(self): 
     self.frame = wx.Frame(None, -1, "TstApp", wx.DefaultPosition, 
     wx.DefaultSize) 

     self.pn = wx.Panel(self.frame, -1) 
     sizer1 = wx.BoxSizer(wx.VERTICAL) 
     self.pn.SetSizer(sizer1) 

     self.pn2 = wx.Panel(self.pn, -1) 
     sizer2 = wx.BoxSizer(wx.VERTICAL) 
     self.pn2.SetSizer(sizer2) 
     sizer1.Add(self.pn2) 

     self.btn = wx.Button(self.pn2, -1, "A Button") 
     sizer2.Add(self.btn) 

     self.frame.Show() 
     self.SetTopWindow(self.frame) 

     return True 

app = TstApp(0) 
app.MainLoop() 

順便說一句,這是更好地要做的widget創建等從wx.Frame派生的類

相關問題