2017-04-07 69 views
2

Tkinter有這些變量類別:BooleanVarDoubleVar,IntVar,StringVar。所有這些方法都有一個trace()方法,允許您附加在變量更改時調用的回調。用Tkinter跟蹤列表

追蹤列表有可能(或有解決方法)?具體來說,我正在尋找一種方法來監控列表,以便我可以更改Treeview的元素。

+0

也許周圍的名單的包裝是什麼你是後:[鏈接](http://stackoverflow.com/questions/37799938/what-happens-when-we-editappend-remove-a-list - 和 - 可以 - 我們 - 執行 - 行動-E)。我想這仍然需要你做一些(重)提升,儘管.... – arrethra

回答

1

下面的代碼包含一個可以刪除的測試函數(forceChange),但是演示了其餘代碼跟蹤一個python列表變量。由於您已經在使用tk事件循環,因此我使用了該循環,但是我還使用調度和時間模塊對其進行了測試,以在沒有GUI時安排事件。

from tkinter import * import sys 

class ListManager: 

    def __init__(self, root, listvar): 
     self.root = root 
     self.listvar = listvar 
     self.previous_value = listvar.copy() 
     # Create an event to watch for changes to the list. 
     self.watch_event = root.after(20, self.watchList) 
     # Create an event to change the list. This is for test purposes only. 
     self.change_event = root.after(200, self.forceChange) 

    def watchList(self): 
     ''' Compare the previous list to the current list. 
      If they differ, print a message (or do something else). 
     ''' 
     try: 
      if self.previous_value != self.listvar: 
       print("Changed! Was:", self.previous_value, " Is:", self.listvar) 
       self.previous_value = self.listvar.copy() 
      # Reschedule this function to continue to check. 
      self.root.after(20, self.watchList) 
     except Exception: 
      print("Variable has been destroyed") 
      self.root.after_cancel(self.change_event) 

    def forceChange(self): 
     try: 
      next = self.listvar[-1:][0] 
     except: 
      # Variable was destroyed. 
      return 
     if next == 11: 
      sys.exit() 
     next += 1 
     self.listvar.append(next) 
     self.root.after(500, self.forceChange) 

if __name__ == '__main__': 
    root = Tk() 
    # This is the list we'll watch. 
    mylist = [1, 2, 3] 
    # Create a list manager 
    vlist = ListManager(root, mylist) 
    root.mainloop()