0
我正在使用Tkinter列表框小部件来跟踪活动用户列表。随着用户登录和注销,此小部件不断更新。每次我更新列表框时,我都会清除整个内容并重新填充它们。每次我这样做,目前的选择都会丢失。我想添加一些逻辑来重新选择在更新列表框之前选择的项目(如果选择了某个项目)。我能够使用get(Tkinter.ACTIVE)获取当前选定的值,并且使用索引(Tkinter.END)插入到列表中后,我可以获取索引。不过,我尝试使用selection_set()和activate(),都没有工作。我也试着在做selection_clear()之前,调用focus()和event_generate(“<>”)并且没有任何效果。这里是我的代码:更新后设置Tkinter列表框选择
def update_userlist(self):
curselection = self.listbox.get(Tkinter.ACTIVE)
print_msg("curselection == " + curselection)
self.listbox.delete(0, Tkinter.END)
for user in self.users:
self.listbox.insert(Tkinter.END, user)
if user == curselection:
selectionindex = self.listbox.index(Tkinter.END)
print_msg("selectionindex == " + str(selectionindex))
else:
selectionindex = None
self.listbox.update()
if selectionindex:
self.listbox.selection_clear(0, Tkinter.END)
self.listbox.selection_set(selectionindex)
self.listbox.activate(selectionindex)
self.listbox.focus()
self.listbox.event_generate("<<ListboxSelect>>")
self.chatframe.update()
我使用Python 2.7。重新填充列表框后,如何重新选择之前选择的值?
这里找到一个可行的解决方案。 http://stackoverflow.com/questions/30391865/keeping-selected-listbox-item-through-re-write – ag415