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

bfo*_*ops 42 python events tkinter

在Tkinter 中有多种方法可以获得回调Text或者Entry更改小部件,但是我没有找到一个用于回调的方法Listbox(我找不到的大部分事件文档是旧的还是不完整的).有没有办法为此生成一个事件?

Pie*_*ert 62

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)
Run Code Online (Sandbox Code Playgroud)

  • 小点,但这只打印所选条目的第一个.如果您有多个选择,请尝试类似"打印"的内容您选择的项目:%s'%[w.get(int(i))for w in w.curselection()]` (4认同)
  • 在Python 3.6.5中,`int(w.curselection()[0])`可以替换为`w.curselection()[0]`,因为它已经返回一个int类型的对象。请注意,我没有在任何其他 Python 版本上尝试过此操作。 (2认同)

Bry*_*ley 47

你可以绑定到:

<<ListboxSelect>>
Run Code Online (Sandbox Code Playgroud)

  • 很好,谢谢.知道在哪里可以找到有关小部件支持的所有自定义事件的文档? (2认同)

Ale*_*lex 5

我遇到的问题是,我需要使用 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()
Run Code Online (Sandbox Code Playgroud)