Hello group,
How do I save user’s selection when using listbox? In the code below, in the function OnOkClick, user’s selection is saved in the frame object’s attriute choice. But after MainLoop, I guess since the frame is destroyed, the attribute becomes None. How do I get around this? Not sure if I made myself understood. Thanks for your help!
import wx
class LstBoxFrame(wx.Frame):
choice = None
def __init__(self, lst, title = "List of items", msg = "Select item"):
wx.Frame.__init__(self, None, -1, title, pos = (300, 200))
panel = wx.Panel(self)
msgLbl = wx.StaticText(panel, -1, msg)
topSizer = wx.BoxSizer(wx.HORIZONTAL)
topSizer.Add(msgLbl,0)
self.okBtn = wx.Button(panel, -1, "Ok")
self.cancelBtn = wx.Button(panel, -1, "Cancel")
btnSizer = wx.BoxSizer(wx.VERTICAL
)
btnSizer.Add(self.okBtn, 0)
btnSizer.Add((10,10), 0)
btnSizer.Add(self.cancelBtn, 0)
self.Bind(wx.EVT_BUTTON, self.OnOkClick, self.okBtn)
self.Bind
(wx.EVT_BUTTON, self.OnCancelClick, self.cancelBtn)
self.listBox = wx.ListBox(panel, -1, (0, 0), (200, 400), lst, wx.LB_SINGLE)
botSizer = wx.BoxSizer(wx.HORIZONTAL)
botSizer.Add(self.listBox, 1, wx.GROW|wx.ALL, 10)
botSizer.Add(btnSizer, 0, wx.EXPAND|wx.ALL, 10)
# mainSizer is the top-level one that manages everything
mainSizer = wx.BoxSizer(wx.VERTICAL)
# now add the sizers to the mainSizer
mainSizer.Add(topSizer, 0, wx.GROW|wx.ALL, 10)
mainSizer.Add(botSizer, 1, wx.EXPAND|wx.ALL, 10)
panel.SetSizer
(mainSizer)
# Fit the frame to the needs of the sizer. The frame will
# automatically resize the panel as needed. Also prevent the
# frame from getting smaller than this size.
mainSizer.Fit(self)
mainSizer.SetSizeHints(self)
def OnOkClick(self, event):
choice = self.listBox.GetStringSelection()
print choice
self.Destroy()
def OnCancelClick(self, event):
choice = None
self.Destroy()
if name == “main”:
lst = [‘zero’, ‘one’, ‘two’, ‘three’, ‘four’, ‘five’,
‘six’, ‘seven’, ‘eight’, ‘nine’, ‘ten’, ‘eleven’,
'twelve', 'thirteen', 'fourteen', 'fifteen']
app = wx.PySimpleApp()
frame = LstBoxFrame(lst)
frame.Show()
print frame.choice
app.MainLoop()
print frame.choice
Regards,
- wcc