wxPython:检查树节点是否有焦点(TreeCtrl)

时间:2013-12-04 00:21:32

标签: python events tree focus wxpython

不要被代码吓倒。这真的很简单。 (如果你愿意,可以运行它)

我正试图找出一种在树节点具有焦点时做某事的方法。我知道如果TreeCtrl具有焦点,我是否想要做某事,那就是:

self.tree.Bind(wx.EVT_SET_FOCUS,some_function)

但我不想要那个,我希望它用于树节点。有什么帮助吗?

对于我的应用程序,弹出窗口将显示所选的每个树节点,并在树节点失去焦点时消失。

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(600, 400))
        self.splitter = wx.SplitterWindow(self, -1)
        self.leftPanel = wx.Panel(self.splitter, -1)
        self.tree = MyTree(self.leftPanel, 1, wx.DefaultPosition, (300, 300))
        self.tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, id=1)

        self.rightPanel = wx.Panel(self.splitter, -1)

        self.splitter.SplitVertically(self.leftPanel, self.rightPanel)

        sizer = wx.BoxSizer ( )
        sizer.Add ( self.splitter, 1, wx.EXPAND )
        self.SetSizer ( sizer )

        self.tree.SetFocus()

    def OnSelChanged(self, event):
        print 'Sel Changed'


class MyTree(wx.TreeCtrl):
    def __init__(self, panel, id, pos, size):
        self.panel = panel
        wx.TreeCtrl.__init__(self, panel, id, pos=pos, size=size, style=wx.TR_HAS_BUTTONS)

        wx.EVT_TREE_ITEM_EXPANDING(self,-1,self.OnItemExpanding)
        wx.EVT_TREE_ITEM_COLLAPSED(self,-1,self.OnItemCollapsed)
        wx.EVT_SET_FOCUS(self,self.OnGotFocus)

        self.root = self.AddRoot('Root')
        self.SetPyData(self.root,0)
        self.SetItemHasChildren(self.root)
        self.Expand(self.root)
        self.SetImageList(wx.ImageList(16,16))

    def OnItemExpanding(self,evt):
        node = evt.GetItem()
        data = self.GetPyData(node)
        if data:
            for i in range(1,2):
                leaf = self.AppendItem(node,'%s.%s' % (data,i))
                self.SetPyData(leaf,'%s.%s' % (data,i))
        else:
            for i in range(1,2):
                leaf = self.AppendItem(node,'%s' % (i))
                self.SetPyData(leaf,'%s' % (i))
                self.SetItemHasChildren(leaf)

    def OnItemCollapsed(self,evt):
        self.DeleteChildren(evt.GetItem())

    def OnGotFocus(self,evt):
        print 'tree got focus'
        evt.Skip()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, "This is a test")
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()

1 个答案:

答案 0 :(得分:0)

我相信你想要

...
    self.tree.Bind(wx.EVT_TREE_SEL_CHANGED,self.OnTreeSelectionChange)
    self.tree.Bind(wx.EVT_KILL_FOCUS,self.OnKillTreeFocus)

...
def OnTreeSelectionChange(self, evt):
    print "OnSelChanged:   ", self.GetItemText(evt.GetItem())