无法理解如何从wxpython的复选框列表中获取数据
我正在尝试从一个检查列表中获取选中的字符串或整数,但我找不到方法。在下面的代码中,你会看到一些没有注释的代码,那些是我尝试过的不同方法。我想把它们留着,以防有人对这些有建议。我对图形用户界面编程和wx库非常陌生。感谢你的帮助。
import wx
class Panel1(wx.Panel):
def __init__(self, parent, log):
wx.Panel.__init__(self, parent, -1)
allLoc = ['One', 'Two', 'Three', 'Four']
wx.StaticText(self, -1, "Choose:", (45, 15))
citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
#self.Bind(wx.EVT_CHECKLISTBOX, self.GetChecks, citList)
#h = citList.GetChecked()
#cities = ()
#v = cities.append(h)
#print h
pos = citList.GetPosition().x + citList.GetSize().width + 25
nextBtn = wx.Button(self, -1, "Next", (pos, 50))
self.Bind(wx.EVT_BUTTON, wx.EvyRadBox2, nextBtn)
#def GetChecks(self, event):
#r = citList.GetId()
#print r
#def printChecks(self, event):
#l = event.CetCheckStrings()
#print l
def EvyRadBox2(self, event):
filepath2 = "c:\\logger2.txt"
file1 = open(filepath2, 'w')
file1.write('%d \n' % event.GetChecked())
file1.close()
app = wx.PySimpleApp()
frame = wx.Frame(None, -1, "Charlie")
Panel1(frame,-1)
frame.Show(1)
app.MainLoop()
**************************编辑********************************
所以我把我的代码改成了这样
import wx
checkedItems = []
class citPanel(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
allLoc = ['One', 'Two', 'Three', 'Four']
wx.StaticText(self, -1, "Choose:", (45, 15))
citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]
class nextButton(wx.Button):
def __init__(self, parent, id, label, pos):
wx.Button.__init__(self, parent, id, label, pos)
class checkList(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(400, 400))
panel = citPanel(self, -1)
nextButton(panel, -1, 'Ok', (275, 50))
self.Bind(wx.EVT_BUTTON, self.Clicked)
self.Centre()
self.Show(True)
def Clicked(self, event):
print checkedItems
event.Skip()
app = wx.App()
checkList(None, -1, 'Charlie')
app.MainLoop()
刚开始这样做的时候,当我点击按钮时,它在wxstdout中抛出了一个“全局名称未定义”的错误。我在顶部添加了检查列表,最开始显示的是空的,现在显示的是一个空列表。任何帮助都非常感谢。
1 个回答
3
checkedItems = [i for i in range(citList.GetCount()) if citList.IsChecked(i)]
citList.GetChecked()
本来应该能帮你完成这个任务。 问题可能出在你试图在 __init__
里获取选中的项目吗?
更新: 你不应该在 __init__
里获取选中的项目,因为那时候用户还不能选择它们。你最好在任何事件处理器里检查,比如 wx.EVT_BUTTON
。
试着更频繁地使用 self
,例如:
self.citList = wx.CheckListBox(self, -1, (60, 50), wx.DefaultSize, allLoc)
# some code
self.panel = citPanel(self, -1)
并把 Clicked
改成:
def Clicked(self, event):
checkedItems = [i for i in range(self.panel.citList.GetCount()) if self.panel.citList.IsChecked(i)]
print checkedItems
event.Skip()
希望这能帮到你。