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

时间:2011-07-02 02:45:07

标签: python events tkinter

在Tkinter中更改TextEntry窗口小部件时,有多种方法可以获得回调,但我找不到Listbox的窗口小部件(它没有帮助我找到的大部分事件文档都是旧的或不完整的。有没有办法为此生成事件?

3 个答案:

答案 0 :(得分: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)

答案 1 :(得分:44)

您可以绑定到:

<<ListboxSelect>>

答案 2 :(得分: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()