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() 
4

2 回答 2

0

您完全错过了“布局管理”主题。我建议阅读 zetcode 教程的布局部分。我已经介绍了wx.BoxSizers 来修复您的示例代码:

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() 

顺便说一句,最好必须在派生的类中创建小部件等wx.Frame

于 2012-09-19T16:52:37.563 回答
0

正如 phineas 已经说过的,您应该只使用 sizer 来排列您的小部件。但是,如果您真的想将多个面板彼此相邻放置,那么您也可以使用 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()
于 2012-09-19T17:35:45.500 回答