WxPython 的控件,除了有Disable() 和 Enable()方法,还有hide及show方法,在固定位置的布局,Hide 和 Show()工作正常 。
比如这样
import wxclass MyButton(wx.Frame):flag = Truedef __init__(self, parent, id, title):wx.Frame.__init__(self, parent, id, title)panel = wx.Panel(self, -1, size=(300, 250))self.btn1 = wx.Button(panel, 201, u'设置', pos=(80, 70))self.Bind(wx.EVT_BUTTON, self.click1, self.btn1)self.btn2 = wx.Button(panel, 202, u'设置2', pos=(180, 70))self.Bind(wx.EVT_BUTTON, self.click2, self.btn2)self.Centre()self.btn2.Hide()def click1(self, e):print("btn1 click!")if self.flag:self.btn2.Hide()self.flag = Falseelse:# self.btn2.Disable()self.btn2.Show()self.flag = Truedef click2(self, e):print("btn2 click!")if __name__ == '__main__':app = wx.App()frame = MyButton(None, -1, u'按钮示例')frame.Show()app.MainLoop()
但如果使用wx.BoxSizer 的 EXPAND 布局 , 如果init 时就隐藏 控件,就会照成错位
比如这样
import wxclass MyButton(wx.Frame):flag = Truedef __init__(self,parent,id,title):wx.Frame.__init__(self,parent,id,title)panel=wx.Panel(self,-1,size=(300,250))box = wx.BoxSizer(wx.HORIZONTAL)self.btn1 = wx.Button(panel, -1, 'Button1')self.btn2 = wx.Button(panel, -1, 'Button2')self.btn3 = wx.Button(panel, -1, 'Button3')box.Add(self.btn1 , 1, wx.ALL, 30)box.Add(self.btn2 , 0, wx.EXPAND)box.Add(self.btn3 , 0, wx.ALIGN_CENTER)self.Bind(wx.EVT_BUTTON, self.click1, self.btn1)self.Bind(wx.EVT_BUTTON, self.click2, self.btn2)panel.SetSizer(box)self.Center()self.btn2.Hide()def click1(self,e ):print("btn1 click!")if self.flag:self.btn2.Hide()self.flag = Falseelse:# self.btn2.Disable()self.btn2.Show()self.flag = Truedef click2(self,e):print("btn2 click!")if __name__=='__main__':app=wx.App()frame=MyButton(None,-1,u'按钮示例')frame.Show()app.MainLoop()
想要这种布局结果,
实际是这种布局结果:
要想控件按预设的位置显示,就不能在init里直接执行 hide 方法。 要在 Frame 显示完成后,再进行隐藏(调用afterload)。
代码优化如下:
# encoding: utf-8
"""
@author: 陈年椰子
@contact: hndm@qq.com
@version: 1.0
@project:test
@file: wxgui3.py
@time: 2022-1-14 11:16说明
"""# coding: utf-8import wxclass MyButton(wx.Frame):flag = Truedef __init__(self,parent,id,title):wx.Frame.__init__(self,parent,id,title)panel=wx.Panel(self,-1,size=(300,250))box = wx.BoxSizer(wx.HORIZONTAL)self.btn1 = wx.Button(panel, -1, 'Button1')self.btn2 = wx.Button(panel, -1, 'Button2')self.btn3 = wx.Button(panel, -1, 'Button3')box.Add(self.btn1 , 1, wx.ALL, 5)box.Add(self.btn2 , 0, wx.EXPAND)box.Add(self.btn3 , 0, wx.ALIGN_CENTER)self.Bind(wx.EVT_BUTTON, self.click1, self.btn1)self.Bind(wx.EVT_BUTTON, self.click2, self.btn2)panel.SetSizer(box)self.Center()def afterload(self):# 根据数据情况再次调整控件self.flag = Falseself.btn2.Hide()def click1(self,e ):print("btn1 click!")if self.flag:self.btn2.Hide()self.flag = Falseelse:self.btn2.Show()self.flag = Truedef click2(self,e):print("btn2 click!")if __name__=='__main__':app=wx.App()frame=MyButton(None,-1,u'按钮示例')frame.Show()# frame 显示完成后,再调整控件frame.afterload()app.MainLoop()