pythonwxpythonwxformbuilder

wxPython : How to change alignment StaticText after SetLabelText


If you create a frame through wxpython and change the contents of the staticText, the alignment will be initialized. How can I solve this problem? I want to align it again.


Solution

  • To dynamically set window alignment flags you have to

    1. Get the wx.Sizer
    2. Find the wx.SizerItem
    3. Set the wx.SizerItem flags via SetFlag
    4. call Sizer.Layout()

    Here's a simple example:

    import wx
    import traceback
    
    
    def run():
        app = wx.App()
        # create the test frame
        frame = wx.Frame(None, title="test frame", size=(500, 500))
    
        # create a simple boxsizer
        sizer = wx.BoxSizer()
        # create the object that we'll be dynamically adjusting
        st = wx.StaticText(frame, label="Click me")
        st.SetFont(wx.Font(30, 74, 90, wx.FONTWEIGHT_BOLD, True, "Arial Rounded"))
        # align the text to the middle initially
        sizer.Add(st, 0, wx.ALIGN_CENTER_VERTICAL)
        frame.SetSizer(sizer)
    
        # bind to an arbitrary event
        st.Bind(wx.EVT_LEFT_DOWN, on_click)
        # do the initial layout and show the frame
        frame.Layout()
        frame.Show()
        app.MainLoop()
    
    
    def on_click(event):
        event.Skip()
        # retrieving the static text object
        st = event.GetEventObject()  # type: wx.StaticText
        # get the sizer that contains this object
        sizer = st.GetContainingSizer()  # type: wx.BoxSizer
        # find the sizer item
        # the sizer item holds the alignment information and tells
        # the sizer how to display this object
        sizer_item = sizer.GetItem(st)  # type: wx.SizerItem
        # alternate between aligning at the top & bottom
        if sizer_item.GetFlag() & wx.ALIGN_BOTTOM:
            print("Setting alignment to top")
            sizer_item.SetFlag(wx.ALIGN_TOP)
        else:
            print("Setting alignment to bottom")
            sizer_item.SetFlag(wx.ALIGN_BOTTOM)
        # call Layout to recalculate the object positions
        sizer.Layout()
    
    
    if __name__ == "__main__":
        try:
            run()
        except:
            traceback.print_exc()
            input()