gpt4 book ai didi

python - TkInter 中小部件的 .pack 和 .configure 之间的区别?

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

我目前正在学习一篇文章,以尝试自学更多关于 TkInter 的知识,因为我正在努力改进我的 Python 3 编程。如有必要,可在此处找到文本:http://www.ferg.org/thinking_in_tkinter/all_programs.html

在标记为“tt040.py”的部分中有一个示例代码,其中的一部分是:

    self.button1 = Button(self.myContainer1)
self.button1["text"] = "Hello, World!" ### (1)
self.button1["background"] = "green" ### (1)
self.button1.pack()


self.button2 = Button(self.myContainer1)
self.button2.configure(text="Off to join the circus!") ### (2)
self.button2.configure(background="tan") ### (2)
self.button2.pack()


self.button3 = Button(self.myContainer1)
self.button3.configure(text="Join me?", background="cyan") ### (3)
self.button3.pack()

这部分代码的解释是:

"(2) 对于 button2,该过程与 button1 基本相同,但我们不访问按钮的字典,而是使用按钮的内置“配置”方法。

(3) 对于 button3,我们看到 configure 方法可以接受多个关键字参数,因此我们可以在一条语句中设置多个选项。"

这个解释到底是什么意思?比如,实际的区别(与 .pack)或 .configure 方法的需要是什么? “按钮的字典”是什么意思?

最佳答案

Tkinter 对象属性不通过 python 属性机制处理(即你可以 self.button1.text = "hello" ) .相反,tkinter 提供了两种更改此属性的方法:

  • 将对象用作字典:self.button1["text"] = "hello"
  • 使用带有命名参数的config方法:self.button1.config(text="hello")

两者是等价的。请注意,您还可以通过名为参数的构造函数传递此类初始化值,以在一步中执行实例化和初始化:self.button1 = Button(self.myContainer1, text="hello")

pack 的用途完全不同。这是一个几何管理指令。在不带参数的情况下使用 button1.pack() 要求将 button1 放在其父窗口小部件中的先例兄弟(如果有)下方。您可以使用 options指定相对位置或调整大小行为。

tkinter 还有其他几何管理器:网格和位置,请参阅 this response进行比较。

关于python - TkInter 中小部件的 .pack 和 .configure 之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8707039/

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