gpt4 book ai didi

python - 在 Python 中表达小部件的层次分组的好方法是什么?

转载 作者:太空狗 更新时间:2023-10-30 02:34:14 25 4
gpt4 key购买 nike

这是一个 Python 风格的问题——我的 Python 代码可以工作,我只是在寻找编码约定的建议,以使代码更易于阅读/理解/调试。

具体来说,我正在开发一个 Python 类,它允许调用者将小部件添加到自定义 GUI。要设置 GUI,用户将编写一个方法,将小部件(命名或匿名)添加到小部件区域,以便小部件形成一棵树(这在 GUI 中很常见)。

为了允许用户设置小部件树而不必为每个容器小部件命名(然后在每次添加子小部件时显式引用该父小部件),我的 API 支持一个概念“父小部件堆栈”。当声明一个容器小部件时,用户可以指定将该小部件推送到这个堆栈上,然后任何其他小部件(没有明确指定父级)将默认添加到堆栈顶部的父级。这是我的意思的一个简单示例:

def SetupGUI(self):
self.AddWidget(name="root", type="container", push=True)

self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="button%i"%i, type="button")
self.PopParentWidget() # pop the buttons-container off the parents-stack

self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="slider%i"%i, type="slider")
self.PopParentWidget() # pop the sliders-container off the parents-stack

self.PopParentWidget() # pop the container "root" off the parents-stack

这很方便,但我发现当 GUI 层次结构变得更加精细时,开始变得难以分辨对 self.PopParentWidget() 的调用对应于哪个容器小部件。很容易输入太多或太少,最终会在 GUI 中产生非常有趣但意想不到的结果。

所以我的问题是,除了强制 PopParentWidget() 使用明确的小部件名称(我想避免这种情况,因为我不想为每个容器小部件命名)之外,我还能做什么吗?代码中的 push/pop 配对看起来更明显?

在 C/C++ 中,我会使用缩进,但在 Python 中,我不允许这样做。例如,我希望能够做到这一点:

def SetupGUI(self):
self.AddWidget(name="root", type="container", push=True)
self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="button%i"%i, type="button")
self.PopParentWidget() # pop the buttons-container off the parents-stack
self.AddWidget(type="container", push=True)
for i in range(0,8):
self.AddWidget(name="slider%i"%i, type="slider")
self.PopParentWidget() # pop the sliders-container off the parents-stack
self.PopParentWidget() # pop the container "root" off the parents-stack

...但是如果我有这样的创意,Python 会抛出一个 IndentationError。

最佳答案

这种情况——你有一对相反的操作——需要a context manager .您可以将容器的子项包装在 with block 中,而不是显式地将容器小部件插入堆栈或从堆栈弹出。建立在你在这里展示的代码之上,这可以像这样实现

@contextlib.contextmanager
def container(self, name=None):
self.AddWidget(name=name, type='container', push=True)
yield
self.PopParentWidget()

(contextlib.contextmanager 的文档)。

然后您的 SetupGUI 方法变为:

def SetupGUI(self):
with self.container(name='root'):
with self.container():
for i in range(0,8):
self.AddWidget(name='button%i' % i, type='button')
with self.container():
for i in range(0,8):
self.AddWidget(name='slider%i' % i, type='slider')

可以看到,从缩进开始嵌套就很清楚了,不需要手动push和pop。

关于python - 在 Python 中表达小部件的层次分组的好方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9305092/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com