wxPython: 单选按钮(RadioButton)在关闭窗口后如何记住我的选择

154 阅读2分钟

使用wxPython开发GUI应用程序时,如何在关闭窗口后记住单选按钮(RadioButton)的选中状态。

huake_00066_.jpg 在wxPython中,当用户在窗口中选择了一个单选按钮,然后关闭窗口,当再次打开窗口时,单选按钮会恢复到其默认状态。这是因为关闭窗口会销毁该窗口及其所有子控件。

2、解决方案

为了记住单选按钮的选中状态,可以使用以下两种方法:

方法1:使用全局变量

import wx

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="单选按钮示例")

        self.radio1 = wx.RadioButton(self, label="选项1", pos=(35, 35))
        self.Bind(wx.EVT_RADIOBUTTON, self.SetLab1, id=self.radio1.GetId())

        self.radio2 = wx.RadioButton(self, label="选项2", pos=(35, 55))
        self.Bind(wx.EVT_RADIOBUTTON, self.SetLab2, id=self.radio2.GetId())

        self.radio3 = wx.RadioButton(self, label="选项3", pos=(35, 75))
        self.Bind(wx.EVT_RADIOBUTTON, self.SetLab3, id=self.radio3.GetId())

        self.button0 = wx.Button(self, label="退出", pos=(115, 142), size=(90, 35))
        self.Bind(wx.EVT_BUTTON, self.OnButton0, self.button0)

        global Delay
        Delay = None

    def SetLab1(self, event):
        global Delay
        Delay = 'A2/'

    def SetLab2(self, event):
        global Delay
        Delay = 'A3/'

    def SetLab3(self, event):
        global Delay
        Delay = 'A4/'

    def OnButton0(self, event):
        self.Hide()

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

在上面的代码中,我们使用了一个全局变量Delay来存储选中的单选按钮的值。当用户选择一个单选按钮时,我们使用SetLab1()SetLab2()SetLab3()函数将Delay变量更新为选中的单选按钮的值。当窗口再次打开时,我们使用if Delay is not None:语句来检查Delay变量是否为None。如果不是None,则使用getattr(self,"radio"+str(int(Delay[1])-1)).SetValue(True)语句来选中与Delay变量中的值相对应的单选按钮。

方法2:使用隐藏窗口

import wx

class MyFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="单选按钮示例")

        self.radio1 = wx.RadioButton(self, label="选项1", pos=(35, 35))
        self.Bind(wx.EVT_RADIOBUTTON, self.SetLab1, id=self.radio1.GetId())

        self.radio2 = wx.RadioButton(self, label="选项2", pos=(35, 55))
        self.Bind(wx.EVT_RADIOBUTTON, self.SetLab2, id=self.radio2.GetId())

        self.radio3 = wx.RadioButton(self, label="选项3", pos=(35, 75))
        self.Bind(wx.EVT_RADIOBUTTON, self.SetLab3, id=self.radio3.GetId())

        self.button0 = wx.Button(self, label="退出", pos=(115, 142), size=(90, 35))
        self.Bind(wx.EVT_BUTTON, self.OnButton0, self.button0)

    def SetLab1(self, event):
        pass

    def SetLab2(self, event):
        pass

    def SetLab3(self, event):
        pass

    def OnButton0(self, event):
        self.Hide()

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

在上面的代码中,我们使用self.Hide()方法来隐藏窗口,而不是关闭窗口。这样,当再次打开窗口时,窗口中的控件将保持其原来的状态。