简体   繁体   中英

How can I resize a staticText to occupy space used by a hidden staticText item in wxPython?

I have a wxPython GUI layout that I would like to be user-configurable. Easiest example would be something like this:

+++++++++++++++++
+ Text1 + Text2 +
+++++++++++++++++

Then I want to add a button that will hide "Text2" and allow "Text1" to overtake that space, being centered horizontally in that space, like this:

+++++++++++++++++
+     Text1     +
+++++++++++++++++

I have tried various things with GridBagSizers and positioning these text controls in various other horizontal and vertical boxsizers, but I can't seem to figure out how to accomplish this. I can get "Text2" to be hidden of course, but it keeps that space reserved for it, meaning that "Text1" still occupies the space to the left and is not centered horizontally in the entire space.

Any ideas?

The key is the Layout() command, to ensure that the sizers recalculate themselves and their children.
Here is an example that will toggle the text:

import wx

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.ID_ANY, "Show/Hide", size=(300,150))

        self.t1 = wx.StaticText(self, -1, ' Text1 ')
        self.t2 = wx.StaticText(self, -1, '  ')
        self.t3 = wx.StaticText(self, -1, ' Text2 ')
        b1 = wx.Button(self, -1, 'Adjust Sizer')

        self.vsizer = wx.BoxSizer(wx.VERTICAL)
        self.hsizer = wx.BoxSizer(wx.HORIZONTAL)
        self.vsizer.Add(wx.StaticText(self, -1, '****************************'), 0, wx.ALIGN_CENTRE_HORIZONTAL, 0)
        self.hsizer.Add(self.t1, 1, 0, 0)
        self.hsizer.Add(self.t2, 0, 0, 0)
        self.hsizer.Add(self.t3, 1, 0, 0)
        self.vsizer.Add(self.hsizer,0,wx.ALIGN_CENTRE_HORIZONTAL)
        self.vsizer.Add(wx.StaticText(self, -1, '****************************'), 0, wx.ALIGN_CENTRE_HORIZONTAL, 0)
        self.vsizer.Add(b1, 0, 0, 0)
        self.Bind(wx.EVT_BUTTON, self.OnAssign)
        self.SetSizer(self.vsizer)
        self.Show()

    def OnAssign(self, event):
        if self.t2.IsShown():
            self.t2.Hide()
            self.t3.Hide()
        else:
            self.t2.Show()
            self.t3.Show()
        self.Layout()

if __name__ == "__main__":
    app = wx.App()
    frame = MyFrame()
    app.MainLoop()

在此处输入图像描述 在此处输入图像描述

You may have to get inventive, if you want the extra * characters in there as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM