wxpythonwxtextctrl

trouble getting wx.TextCtrl contents to re-center on resize


I have a TextCtrl with style=wx.TE_CENTRE, and I want/expect its contents to remain centered when I resize the TextCtrl. However, the text stays on the left side of the TextCtrl.

import wx

class MyApp(wx.App):
    def OnInit(self):
        frame = wx.Frame(None)
        frame.Show(True)
        self.SetTopWindow(frame)
        self.myText = wx.TextCtrl(frame, value="A", style=wx.TE_CENTRE)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(self.myText, wx.EXPAND)

        frame.SetSizer(sizer)
        sizer.Fit(frame)

        self.Bind(wx.EVT_SIZE, self.OnSize)
        return True

    def OnSize(self, evt):
        self.myText.SetValue("after resize")

myApp = MyApp(0)
myApp.MainLoop()

After a lot of trial and error, I got it to work by doing both of the following:

Why are both of these necessary? I'd like to understand what I'm doing wrong here. (I'm using wxPython 4.0.4 on Win7.)


Solution

  • It may be your environment, it certainly works normally on Linux using wx 4.0.4
    It could be down to the fact that you are doing it all within a wx.App class.
    Conventionally this code would be written something like this:

    import wx
    
    class MyFrame(wx.Frame):
        def __init__(self,parent):
            wx.Frame.__init__(self,parent,-1,("My Frame"), size=(200,100))
            self.myText = wx.TextCtrl(self, value="A", style=wx.TE_CENTRE)
            sizer = wx.BoxSizer(wx.HORIZONTAL)
            sizer.Add(self.myText, wx.EXPAND)
            self.SetSizer(sizer)
            self.Show()
    
    myApp = wx.App()
    frame = MyFrame(None)
    myApp.MainLoop()
    

    Does this code misbehave in the same way?