如何在wxPython中使用GridBagSizer滚动Panel

时间:2015-03-07 15:56:28

标签: python wxpython scrollable gridbagsizer

我需要制作一个Panel可滚动。我用GridBagSizer

代码:

import wx

class MyFrame( wx.Frame ):
    def __init__( self, parent, ID, title ):
        wx.Frame.__init__( self, parent, ID, title, wx.DefaultPosition, wx.Size( 400, 300 ) )

        self.InitUI()
        self.Center()
        self.Show()


    def InitUI(self):

        MPanel = wx.Panel(self)
        GridBag = wx.GridBagSizer(2, 2)


        CO = ["RED", "BLUE"]

        for i in range(10):

            X = wx.StaticText(MPanel, size=(50,50), style=wx.ALIGN_CENTER, label="")
            X.SetBackgroundColour(CO[i%2])
            GridBag.Add(X, pos=(i+1, 1), flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=1)

        GridBag.AddGrowableCol(1)
        MPanel.SetSizerAndFit(GridBag)

class MyApp( wx.App ):
    def OnInit( self ):
        self.fr = MyFrame( None, -1, "K" )
        self.fr.Show( True )
        self.SetTopWindow( self.fr )
        return True


app = MyApp( 0 )
app.MainLoop()

我该怎么做?

1 个答案:

答案 0 :(得分:1)

尝试以下解决方案可以帮助您:

import wx
import wx.lib.scrolledpanel as scrolled
class MyPanel(scrolled.ScrolledPanel):

    def __init__(self, parent):
        scrolled.ScrolledPanel.__init__(self, parent, -1)
        self.SetAutoLayout(1)
        self.SetupScrolling()

现在不使用MPanel=wx.Panel(self),而是使用`MPanel = MyPanel(self),其余的代码将保持不变。

以下是修改后的代码:

class MyFrame( wx.Frame ):
    def __init__( self, parent, ID, title ):
        wx.Frame.__init__( self, parent, ID, title, wx.DefaultPosition, wx.Size( 400, 300 ) )

        self.InitUI()
        self.Center()
        self.Show()

    def InitUI(self):

        MPanel = MyPanel(self)
        GridBag = wx.GridBagSizer(2, 2)

        CO = ["RED", "BLUE"]

        for i in range(10):
            X = wx.StaticText(MPanel, size=(50,50), style=wx.ALIGN_CENTER, label="")
            X.SetBackgroundColour(CO[i%2])
            GridBag.Add(X, pos=(i+1, 1), flag=wx.EXPAND|wx.LEFT|wx.RIGHT, border=1)

        GridBag.AddGrowableCol(1)
        MPanel.SetSizerAndFit(GridBag)

class MyApp( wx.App ):
    def OnInit( self ):
        self.fr = MyFrame( None, -1, "K" )
        self.fr.Show( True )
        self.SetTopWindow( self.fr )
        return True

app = MyApp( 0 )
app.MainLoop()