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

2024-03-29 14:46:57 发布

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

当Tkinter中的TextEntry小部件发生更改时,有很多方法可以获得回调,但我还没有找到适合Listbox的回调(这无助于我找到的大部分事件文档是旧的或不完整的)。有什么方法可以生成事件吗?


Tags: 方法text文档部件tkinter事件entrylistbox
3条回答
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)

我遇到了一个问题,需要在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()

您可以绑定到:

<<ListboxSelect>>

相关问题 更多 >