当在Tkinter中更改Text
或Entry
小部件时,有很多方法可以获得回调,但我没有为Listbox
找到一个(这对我能找到的大部分事件文档是旧的还是不完整没有帮助)。有没有办法为此生成一个事件?
你可以绑定到:
<<ListboxSelect>>
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()