使用Tkinter跟踪列表

时间:2017-04-07 14:31:10

标签: python python-3.x tkinter

Tkinter有以下变量类:BooleanVarDoubleVarIntVarStringVar。所有这些方法都有trace()方法,允许您附加变量更改时调用的回调。

跟踪列表是否可能(或有解决方法)?具体来说,我正在寻找一种监视列表的方法,以便我可以更改Treeview的元素。

1 个答案:

答案 0 :(得分:1)

下面的代码包含一个可以删除的测试函数(forceChange),但演示了其余的代码跟踪python列表变量。由于你已经使用了tk事件循环,我使用了它,但我还使用sched和time模块测试它,以便在没有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()