wxpython中的对象对齐

alignment of objects in wxpython

我向 BoxSizer 添加了一些按钮。 这是我想要的:

这就是我要去的地方:

这是第二个盒子的代码:

    self.approveItem = wx.Button(self.panel_1, -1, "Approve Item")
    self.changeQty = wx.Button(self.panel_1, -1, "Change Qty")
    sizer_2 = wx.BoxSizer(wx.HORIZONTAL)
    sizer_2.Add(self.approveItem, 0, wx.ALIGN_RIGHT | wx.RIGHT, 0)
    sizer_2.Add(self.changeQty, 0, wx.ALIGN_RIGHT| wx.RIGHT, 0)
    self.sizer_item_staticbox = wx.StaticBox(self, -1, "")
    sizer_item = wx.StaticBoxSizer(self.sizer_item_staticbox, wx.HORIZONTAL)
    sizer_item.SetMinSize((600,-1))
    sizer_item.Add(sizer_2, 0, wx.EXPAND, 0)    

我该如何解决?

下面的代码会给出你想要的结果。

但是请注意,对齐是通过设置比例和添加一个垫片来完成的,垫片会将按钮推向右侧。我发现这 understandable/readable 比摆弄对齐标志要多得多。

    # Defining panel
    self.panel_1 = wx.Panel(self,-1)

    # create dummy button quick
    quickbtn = lambda label: wx.Button(self.panel_1, -1, label)

    stat1 = wx.StaticBox(self.panel_1, -1)
    stsz1 = wx.StaticBoxSizer(stat1, wx.HORIZONTAL)
    stsz1.Add((0,0), 1) # dummy spacer with proportion 1 filling the space on the left
    stsz1.Add(quickbtn('btn1'), 0, wx.EXPAND)

    stat2 = wx.StaticBox(self.panel_1, -1)
    stsz2 = wx.StaticBoxSizer(stat2, wx.HORIZONTAL)
    stsz2.Add((0,0), 1)
    stsz2.Add(quickbtn('btn2_A'), 0, wx.EXPAND)
    stsz2.Add(quickbtn('btn2_B'), 0, wx.EXPAND)

    szmain = wx.BoxSizer(wx.VERTICAL)
    szmain.Add(stsz1, 0, wx.EXPAND|wx.ALL, 2)
    szmain.Add(stsz2, 0, wx.EXPAND|wx.ALL, 2)

    self.panel_1.SetSizer(szmain)

有很多方法可以实现您想要的效果,包括使用 flexgridsizer、gridsizer 以及普通的水平和垂直 boxsizer,这里是一个 gridsizer 示例。
我将其设置为 5 列宽,以便您可以根据需要在左侧插入额外的按钮。
参见:http://wxpython.org/Phoenix/docs/html/GridSizer.html

#!/usr/bin/env python
import wx
class MyFrame(wx.Frame):
    def __init__(self, parent, ID, title):
        wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition)
        Buttons = []
        Buttons.append(wx.Button(self,-1, "Approve Location"))
        Buttons.append(wx.Button(self,-1, "Approve Item"))
        Buttons.append(wx.Button(self,-1, "Change Qty"))
        Buttons.append(wx.Button(self,-1, "Approve"))
        sizer = wx.GridBagSizer(5,3)
        sizer.Add(Buttons[0], (0, 5), (1,1), wx.EXPAND)
        sizer.Add(Buttons[1], (1, 4), (1,1), wx.EXPAND)
        sizer.Add(Buttons[2], (1, 5), (1,1), wx.EXPAND)
        sizer.Add(Buttons[3], (2, 5), (1,1), wx.EXPAND)
        self.SetSizerAndFit(sizer)
        self.Centre()
class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, "Gridbagsizer")
        frame.Show(True)
        self.SetTopWindow(frame)
        return True
if __name__ == "__main__":
    app = MyApp(0)
    app.MainLoop()