Skip to main content
 首页 » 编程设计

python之使用 Tkinter 跟踪列表

2025年02月15日7lyj

Tkinter 有这些变量类:BooleanVar、DoubleVar、IntVar、StringVar。它们都有一个 trace() 方法,允许您附加一个在变量更改时调用的回调。

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

请您参考如下方法:

下面的代码包括一个可以删除的测试函数 (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()