简体   繁体   中英

wxPython: centering an image in a panel

I have a GridSizer with StaticBitmap images in it. I want to put each of the images in their own panels so I can change the background color to highlight an image if it has been selected. When I try to do this, however, the images are not centered in their panels and the highlighted background color is only present on two borders. How can I make the images in the center of their panels so there is an equivalent border around all sides of each?

sizer = wx.GridSizer(rows=row,cols=cols,vgap=5)
for fn in filenames:
    p = wx.Panel(self.panel)
    img = wx.Image(fn, wx.BITMAP_TYPE_ANY)
    img2 = wx.StaticBitmap(p, wx.ID_ANY, wx.BitmapFromImage(img))
    img2.Bind(wx.EVT_LEFT_DOWN, self.OnClick, img2)
    sizer.Add(p)
self.panel.SetSizer(sizer)

You need to add your image to a boxSizer with a border. You could write an imagePanel class to implement this.

You should then be able to call SetBackgroundColour on your ImgPanels to change the borders (panels) colour when ever you need to.

Here's a very rough example for an ImgPanel class

class ImgPanel(wx.Panel):
    def __init__(self, parent, image):
        wx.Panel.__init__(self, parent)

        img = wx.Image(image, wx.BITMAP_TYPE_ANY)
        self.sBmp = wx.StaticBitmap(self, wx.ID_ANY, wx.BitmapFromImage(img))

        sizer = wx.BoxSizer()
        sizer.Add(item=self.sBmp, proportion=0, flag=wx.ALL, border=10)
        self.SetBackgroundColour('green')
        self.SetSizerAndFit(sizer)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM