我昨天正在实现一个 ttk 进度条,看到一些我不太理解的代码。
可以使用如下所示的方法设置进度条的最大值:
progress_bar["maximum"] = max
我期望 ttk Progressbar 对象会使用实例变量来跟踪创建的对象的最大值,但该语法看起来更像是:
progres_bar.maximum = max
所以我的问题是,这里的括号语法到底发生了什么,术语是什么,我在哪里可以阅读更多相关内容?当我查看 Progressbar 类时,我看到的只是
class Progressbar(Widget):
"""Ttk Progressbar widget shows the status of a long-running
operation. They can operate in two modes: determinate mode shows the
amount completed relative to the total amount of work to be done, and
indeterminate mode provides an animated display to let the user know
that something is happening."""
def __init__(self, master=None, **kw):
"""Construct a Ttk Progressbar with parent master.
STANDARD OPTIONS
class, cursor, style, takefocus
WIDGET-SPECIFIC OPTIONS
orient, length, mode, maximum, value, variable, phase
"""
Widget.__init__(self, master, "ttk::progressbar", kw)
我看到有一个“小部件特定选项”,但我不明白 progress_bar["maximum"] = max
如何设置该值,或者如何存储它。
最佳答案
发生的情况是 ttk 模块是安装了 tk 软件包的 tcl 解释器的薄包装器。 Tcl/tk 没有 python 类的概念。
在 tcl/tk 中,设置属性的方法是通过函数调用。例如,要设置最大属性,您可以执行以下操作:
.progress_bar configure -maximum 100
ttk 包装器非常相似:
progress_bar.configure(maximum=100)
由于只有原始 tkinter 开发人员知道的原因,他们决定实现一个允许您使用括号表示法的字典接口(interface)。也许他们认为这更Pythonic?例如:
progress_bar["maximum"] = 100
几乎可以肯定,他们没有为对象创建这些属性(例如:progress_bar.maximum = 100
)的原因是因为某些 tcl/tk 小部件属性会与 python 保留字或标准冲突属性(例如,id
)。通过使用字典,他们可以避免此类冲突。
关于Python ttk 对象 - 不理解小部件特定的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30732579/