wxPython:对齐两个 boxsizers 中的元素

wxPython: Aligning the elements within two boxsizers

我想对齐 boxsizers 的两个元素,即:"BIG BIG STRINNNNNNGGGGGGGGG" 和 "Measurement",以便它们位于同一列下,如下所示:

hello world                                Measurement
oh no worldBIG BIG STRINNNNNNGGGGGGGGGGGGGGGGGGGGGGGGG

如何使用以下代码实现此目的?

阅读 wxPython 文档,它说了以下内容:

The ALIGN* flags allow you to specify the alignment of the item within the space allotted to it by the sizer, adjusted for the border if any.

然而,在这种情况下情况并非如此。

import wx
from imgtec import codescape
import wx.lib.inspection

class MyRegion(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title="My Region")
        b1=wx.BoxSizer(orient=wx.HORIZONTAL)
        b2=wx.BoxSizer(orient=wx.HORIZONTAL)

        d1 = wx.StaticText(self, label="hello world")
        b1.Add(d1)
        d2 = wx.StaticText(self, label="Measurement", style=wx.ALIGN_RIGHT)
        b1.Add(d2,
               flag=wx.ALIGN_RIGHT | wx.EXPAND)

        c1 = wx.StaticText(self, label="oh no world")
        b2.Add(c1)
        c2 = wx.StaticText(self, label="BIG BIG STRINNNNNNGGGGGGGGGGGGGGGGGGGGGGGGG",style=wx.ALIGN_RIGHT)
        b2.Add(c2,
           flag=wx.ALIGN_RIGHT| wx.EXPAND )

        sizer = wx.GridBagSizer()
        sizer.Add(item=b2, pos=(0,0), flag=wx.EXPAND)
        sizer.Add(item=b1, pos=(1,0), flag=wx.EXPAND)
        self.SetSizer(sizer)


if __name__ == "__main__":
    app = wx.App()
    frame = MyRegion(None)
    frame.Show()
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

你只需要在d1d2之间添加一个间隔符:

import wx
import wx.lib.inspection

class MyRegion(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, title="My Region")
        b1=wx.BoxSizer(orient=wx.HORIZONTAL)
        b2=wx.BoxSizer(orient=wx.HORIZONTAL)

        d1 = wx.StaticText(self, label="hello world")
        b1.Add(d1)

        b1.AddStretchSpacer()  # <-- ADD THE SPACER HERE

        d2 = wx.StaticText(self, label="Measurement", style=wx.ALIGN_RIGHT)
        b1.Add(d2,
               flag=wx.ALIGN_RIGHT | wx.EXPAND)

        c1 = wx.StaticText(self, label="oh no world")
        b2.Add(c1)
        c2 = wx.StaticText(self, label="BIG BIG STRINNNNNNGGGGGGGGGGGGGGGGGGGGGGGGG",style=wx.ALIGN_RIGHT)
        b2.Add(c2,
           flag=wx.ALIGN_RIGHT| wx.EXPAND )

        sizer = wx.GridBagSizer()
        sizer.Add(item=b2, pos=(0,0), flag=wx.EXPAND)
        sizer.Add(item=b1, pos=(1,0), flag=wx.EXPAND)
        self.SetSizer(sizer)


if __name__ == "__main__":
    app = wx.App()
    frame = MyRegion(None)
    frame.Show()
    wx.lib.inspection.InspectionTool().Show()
    app.MainLoop()

Mike Driscoll 的回答已经显示了正确的方法,我想补充一点,要记住一个简单的规则:对齐标志只在横向 sizer 方向上起作用,即垂直对水平盒子大小。

wxWidgets 的未来版本将在水平尺寸器中使用 wxALIGN_RIGHT 时出错(并且,类似地,wxALIGN_TOP 或垂直尺寸器中的其他垂直对齐方式),因为这可以 从不 工作。

然而,您可以在 2D sizer 中使用双向对齐标志,例如 wx[Flex]GridSizer