如何从CustomTreeCtrl获取复选框选择

时间:2012-06-01 20:42:34

标签: python wxpython

我正在使用带有复选框的CustomTreeCtrl,我无法弄清楚如何确定选择了哪些复选框。我看了http://xoomer.virgilio.it/infinity77/wxPython/Widgets/wx.TreeCtrl.html#GetSelection并将它们放在一起:

import string
import os
import sys
import wx
import wx.lib.agw.customtreectrl as CT

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, "CustomTreeCtrl Demo")        

        custom_tree = CT.CustomTreeCtrl(self, agwStyle=wx.TR_DEFAULT_STYLE)
        root = custom_tree.AddRoot("The Root Item")

        for y in range(5):
            last = custom_tree.AppendItem(root, "item %d" % y)

            for z in range(5):
                item = custom_tree.AppendItem(last,  "item %d" % z, ct_type=1)

            self.Bind(CT.EVT_TREE_ITEM_CHECKED, self.ItemChecked)

    def ItemChecked(self, event):
            print("Somebody checked something")
            print(event.GetSelections())

app = wx.PySimpleApp()
frame = MyFrame(None)
app.SetTopWindow(frame)
frame.Show()
app.MainLoop()

当我选中一个方框时,我得到了Traceback:“AttributeError:'TreeEvent'对象没有属性'GetSelections'”任何有关如何读取选中框的建议都会很棒!

1 个答案:

答案 0 :(得分:1)

有问题的event对象没有GetSelections方法。它有GetSelection,它会告诉您在该事件中选择了哪个项目。如果您想要在ItemChecked中获取所有选定的项目,请将custom_tree重命名为self.custom_tree,然后您可以在self.custom_tree.GetSelections()内拨打ItemChecked。< / p>

如果将来您想知道某些事件对象可以使用哪种方法,可以将print(dir(event))放在处理程序中。

自定义树控件没有获取已检查项的方法。您可以做的一件事是在框架中创建一个self.checked_items列表,并将其保留在ItemChecked方法中。此列表可以包含项目的字符串值或项目本身。例如,

class MyFrame(wx.Frame):
    def __init__(self, parent):
        # ....
        self.checked_items = []
        # ....

    def ItemChecked(self, event):
        if event.IsChecked():
            self.checked_items.append(event.GetItem())
            # or to store the item's text instead, you could do ...
            # self.checked_items.append(self.custom_tree.GetItemText(event.GetItem()))
        else:
            self.checked_items.remove(event.GetItem())
            # or ... 
            # self.checked_items.remove(self.custom_tree.GetItemText(event.GetItem()))