如何在TKinter列表框中选择多个项目?

2024-06-26 14:11:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从一个Listbox中选择多个项目,在选择时按shift键似乎很直观,可以选择一组项目,但Tkinter中似乎没有内置的功能。在

所以我试图自己实现它,通过注册shift键并获得最新的选择。但是我在试图找出Listbox中的最新选择时遇到了麻烦。listbox.get(ACTIVE)似乎落后于我的预期。在

以下是我迄今为止所做的努力,我意识到当我知道最新的选择时,我需要做更多的事情,但那会在以后发生。在

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)

Tags: 项目selfeventgetshiftisbindtkinter
1条回答
网友
1楼 · 发布于 2024-06-26 14:11:36

您似乎想要的行为实际上是默认情况下可用的,使用

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还没有更新。在

相关问题 更多 >