如何在树状序列中构建一个字符串变量结构

2024-04-23 14:08:43 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

这能做到吗


Tags: 目标结构树状stringvar
1条回答
网友
1楼 · 发布于 2024-04-23 14:08:43

我为这个树状结构编写了一个类:

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)

相关问题 更多 >