Search code examples
pythonwxpython

How can I center the text I just changed?


There is a static text in the center, which by clicking on the button changes to a random text from file.

And here's the problem itself: after pressing the button, the new text starts from the beginning of the previous peace text, not in the center.

How can the problem be solved?

import wx
import random

class TestWindow(wx.Frame):

    def chBtnClick(self, event):
        f = open("Words.txt", "r")
        random_word = random.choice(f.read().split("\n"))
        self.chText.SetLabel(random_word)
        
    def __init__(self, parent, title):
        wx.Frame.__init__(self, None, title=title, size=(300, 200))

        self.panel = wx.Panel(self, wx.ID_ANY)

        VSizer = wx.BoxSizer(wx.VERTICAL)

        self.chText = wx.StaticText(self.panel, wx.ID_ANY, label="Click Random")
        VSizer.Add(self.chText, 0, wx.CENTER | wx.ALL, 5)
        
        self.chBtn = wx.Button(self.panel, wx.ID_ANY, label="Random!")
        VSizer.Add(self.chBtn, 0, wx.CENTER|wx.ALL, 5)

        self.chBtn.Bind(wx.EVT_BUTTON, self.chBtnClick)

        self.panel.SetSizer(VSizer)
        self.Centre()
        self.Show()

if __name__ == "__main__":
    app = wx.App()
    frame = TestWindow(None, "ExBurate Test ver.")
    app.MainLoop()

Before button

Images before buttom

After button

and after


Solution

  • After change the text call self.panel.Layout() to re-center object

    def chBtnClick(self, event):
        f = open("Words.txt", "r")
        random_word = random.choice(f.read().split("\n"))
        self.chText.SetLabel(random_word)
        self.panel.Layout()