wxpython:为什么当Shift键按下时我不能签入wx.CheckListBox?

时间:2018-12-06 17:13:40

标签: wxpython keyevent checklistbox

我打算在按住Shift键的同时进行一系列选择。但是,当按下Shift键时,不会触发wx.EVT_CHECKLISTBOX。以下是我的代码:

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, -1, "Different Frame", size=(300, 300))
        panel = wx.Panel(self)
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.prevIndex = None
        self.shift_down = False
        self.level = wx.CheckListBox(panel, -1)
        levels = ["%s" % i for i in range(9)]
        self.level.SetItems(levels)
        self.level.Bind(wx.EVT_CHECKLISTBOX, self.OnSelectLevel)
        self.level.Bind(wx.EVT_KEY_DOWN, self.onKeyDown)
        self.level.Bind(wx.EVT_KEY_UP, self.onKeyUp)

        panel.SetSizer(sizer)
        self.Centre()
        self.Show()

    def onKeyDown(self, event):
        print("onKeyDown")
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_SHIFT:
            self.shift_down = True
        else:
            event.Skip()

    def onKeyUp(self, event):
        print("onKeyUp")
        keycode = event.GetKeyCode()
        if keycode == wx.WXK_SHIFT: 
            self.shift_down = False
        else:
            event.Skip()

    def OnSelectLevel(self, evt):
        print("OnSelectLevel")
        currindex = evt.GetInt()
        currCheckedItems = self.level.GetCheckedItems()
        if self.prevIndex != None and self.shift_down == True:
            if currindex > self.prevIndex:
                newrange = list(range(self.prevIndex, currindex))
            else:
                newrange = list(range(currindex, self.prevIndex, -1))
            newCheckedItems = currCheckedItems + newrange
            self.level.SetCheckedItems(newCheckedItems)
            self.prevIndex = currindex
            evt.Skip()

app = wx.App(0)
frame = MyFrame(None)
frame.Show()
app.MainLoop()

反正是有触发事件wx的地方。按住Shift键的同时按下EVT_CHECKLISTBOX?谢谢。

1 个答案:

答案 0 :(得分:1)

您的属性self.prevIndex从未设置。 尝试此修改:

def OnSelectLevel(self, evt):
    currindex = evt.GetInt()
    currCheckedItems = list( self.level.GetCheckedItems() )
    if self.prevIndex != None and self.shift_down == True:
        if currindex > self.prevIndex:
            newrange = list(range(self.prevIndex, currindex))
        else:
            newrange = list(range(currindex, self.prevIndex, -1))
        newCheckedItems = currCheckedItems + newrange
        self.level.SetCheckedItems(newCheckedItems)
    self.prevIndex = currindex
    evt.Skip()

此外,使用wx.GetKeyState(wx.WXK_SHIFT)仅在OnSelectLevel中检查是否按下Shift键会更容易。

通常,我总是建议使用良好的调试器并在事件处理程序中设置断点。然后,您可以交互式检查事物并逐步执行。