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() 方法中的值來配置這些小部件的屬性。
廣告