如何以树的顺序构建StringVar结构

时间:2016-12-22 13:04:17

标签: python tkinter tree

我想构建一个StringVar的树状结构。下图(希望)描述了我想要实现的目标。

                          A
                        /   \
                       /     \
                      B       C
                     / \
                    /   \
                   D     E 

B中的任何变化都应该触发他下面的其他StringVar(D和E)的变化,但是,它不应该触发A的变化。

可以这样做吗?

1 个答案:

答案 0 :(得分:0)

我为这个类似树的结构写了一个类:

from tkinter import Tk, StringVar

class StringVarTree:
    """ Tree of StringVars """
    def __init__(self, node, left=None, right=None):
        """ 
            node: StringVar 
            left: StringVarTree or None
            right: StringVarTree or None 
        """
        self.node = node 
        self.left = left 
        self.right = right

    def __repr__(self):
        return "%s [%s %s]" % (self.node.get(), self.left, self.right)

    def set(self, string):
        # modify the node
        self.node.set(string)
        # propagate the modification to all branches below the node
        if self.left:
            self.left.set(string)
        if self.right:
            self.right.set(string)


if __name__ == '__main__':
    root = Tk()
    A = StringVar(root, "A")
    B = StringVar(root, "B")
    C = StringVar(root, "C")
    D = StringVar(root, "D")
    E = StringVar(root, "E")
    # tree of StringVars
    tree = StringVarTree(A, StringVarTree(B, StringVarTree(D), StringVarTree(E)), StringVarTree(C))
    # thanks to the __repr__ method, we can see the tree
    print(tree)
    # now let's modify the B branch
    tree.left.set("b")
    print(tree)