更改Tkinter列表框选择时获取回调?

问题描述 投票:40回答:3

当在Tkinter中更改TextEntry小部件时,有很多方法可以获得回调,但我没有为Listbox找到一个(这对我能找到的大部分事件文档是旧的还是不完整没有帮助)。有没有办法为此生成一个事件?

python events tkinter
3个回答
44
投票

你可以绑定到:

<<ListboxSelect>>

58
投票
def onselect(evt):
    # Note here that Tkinter passes an event object to onselect()
    w = evt.widget
    index = int(w.curselection()[0])
    value = w.get(index)
    print 'You selected item %d: "%s"' % (index, value)

lb = Listbox(frame, name='lb')
lb.bind('<<ListboxSelect>>', onselect)

2
投票

我有一个问题,我需要使用selectmode = MULTIPLE获取列表框中的最后一个选定项目。如果其他人有同样的问题,这就是我做的:

lastselectionList = []
def onselect(evt):
    # Note here that Tkinter passes an event object to onselect()
    global lastselectionList
    w = evt.widget
    if lastselectionList: #if not empty
    #compare last selectionlist with new list and extract the difference
        changedSelection = set(lastselectionList).symmetric_difference(set(w.curselection()))
        lastselectionList = w.curselection()
    else:
    #if empty, assign current selection
        lastselectionList = w.curselection()
        changedSelection = w.curselection()
    #changedSelection should always be a set with only one entry, therefore we can convert it to a lst and extract first entry
    index = int(list(changedSelection)[0])
    value = w.get(index)
    tkinter.messagebox.showinfo("You selected ", value)
listbox = tk.Listbox(frame,selectmode=tk.MULTIPLE)
listbox.bind('<<ListboxSelect>>', onselect)
listbox.pack()
© www.soinside.com 2019 - 2024. All rights reserved.