如何在 TKinter 列表框中移动 select 多个项目?

How can I shift select multiple items in TKinter listbox?

我正在尝试 select 来自 Listbox 的多个项目,在 selecting 时按 shift 键并selected 一个项目块似乎很直观,但在 Tkinter 中似乎没有内置功能。

所以我尝试自己实现它,方法是注册 shift 键并获取最新的 selection。但是我在尝试找出 Listbox 中最新的 selection 时遇到了困难。 listbox.get(ACTIVE) 似乎比我预期的差了一位。

这是我到目前为止尝试做的事情,我知道当我知道最新的 selection 时我需要做更多的事情,但那会在以后出现。

from Tkinter import *

class GUI():
    def __init__(self,frame): # Some Init
        self.listbox = Listbox(root, height=20, width=51, selectmode=MULTIPLE, exportselection=0, yscrollcommand=yscrollbar.set, xscrollcommand=xscrollbar.set)
        # -- Some Grid setup here --
        self.listbox.bind("<<ListboxSelect>>", self.selectionCallback)
        frame.bind("<Shift_L>", self.shiftCallback)
        frame.bind("<KeyRelease-Shift_L>", self.shiftCallback)

    def selectionCallback(self,event):
        print self.listbox.get(ACTIVE) # This is where im stuck

    def shiftCallback(self,event):
        if event.type is 2: #KeyPress
            self.shift = True
        elif event.type is 3: #KeyRelease
            self.shift = False

if __name__ == "__main__":
    root = Tk()
    GUI(root)

您实际上想要的行为 默认可用的,请使用

Listbox(..., selectmode=EXTENDED, ...)

来自effbot

The listbox offers four different selection modes through the selectmode option. These are SINGLE (just a single choice), BROWSE (same, but the selection can be moved using the mouse), MULTIPLE (multiple item can be choosen, by clicking at them one at a time), or EXTENDED (multiple ranges of items can be chosen, using the Shift and Control keyboard modifiers). The default is BROWSE. Use MULTIPLE to get “checklist” behavior, and EXTENDED when the user would usually pick only one item, but sometimes would like to select one or more ranges of items.


至于listbox.get(ACTIVE)ACTIVE的项目是有下划线的。您可以看到这仅在释放鼠标按钮时更新。因为 <<ListboxSelect>> 事件是在鼠标按下时触发的,所以你得到了之前选择的项目,因为 ACTIVE 还没有更新。