2017-02-25 33 views
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。重新填充列表框後,如何重新選擇之前選擇的值?

+0

這裏找到一個可行的解決方案。 http://stackoverflow.com/questions/30391865/keeping-selected-listbox-item-through-re-write – ag415

回答