Tkinter 中 Widget 的 .pack 和 .configure 方法的区别


我们使用各种几何管理器将小部件放置在 tkinter 窗口上。几何管理器告诉应用程序在窗口中在哪里以及如何组织小部件。使用几何管理器,您可以配置应用程序窗口中小部件的大小和坐标。

pack() 方法是 tkinter 中三种几何管理器之一。其他几何管理器是 grid()place()pack() 几何管理器通常用于提供填充并提供一种在窗口中排列小部件的方法。

要显式配置定义后小部件的属性,可以使用 configure() 方法。configure() 方法还用于配置小部件属性,包括调整大小和排列属性。

示例

在下面的示例中,我们创建了一个 Label 小部件和一个 Button 小部件。可以使用 pack()configure() 方法有效地配置这两个小部件的属性。

# Import required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Define a function
def close_win():
   win.destroy()

# Create a label
my_label=Label(win, text="Hey Everyone!", font=('Arial 14 bold'))
my_label.pack(pady= 30)

# Create a button
button= Button(win, text="Close")
button.pack()

# Configure the label properties
my_label.configure(bg="black", fg="white")
button.configure(font= ('Monospace 14 bold'), command=close_win)

win.mainloop()

输出

运行以上代码将显示一个包含 Button 和 Label 小部件的窗口。您可以通过操作 configure() 方法中的值来配置这些小部件的属性。

更新于: 2021年12月22日

1K+ 次浏览

开启你的 职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.