如何使用tkinter將物件放置在框架的中間?


要將物件放置在框架的中間,我們可以使用**place**方法。讓我們舉個例子看看它是如何實現的。

步驟 -

  • 匯入所需的庫並建立tkinter框架的例項。

  • 使用**win.geometry**方法設定框架的大小。

  • 接下來,建立一個按鈕併為其新增標籤。

  • 使用place方法透過提供**x**和**y**座標值來設定按鈕的位置。

  • 將小部件的中心放置在按鈕小部件相對x和y位置的**0.5**處**(relx=0.5, rely=0.5)**。透過提供**"anchor=CENTER"**將錨點設定為中心。

  • 最後,執行應用程式視窗的**mainloop**。

示例

# Import the Tkinter library
from tkinter import *
from tkinter import ttk

# Create an instance of Tkinter frame
win = Tk()

# Define the geometry
win.geometry("750x350")

# Create Buttons in the frame
button = ttk.Button(win, text="Button at the Center")
button.place(relx=0.5, rely=0.5, anchor=CENTER)

win.mainloop()

輸出

執行此程式碼時,將顯示以下輸出視窗 -

現在,嘗試調整視窗大小,您會注意到按鈕小部件會自動相應地居中。

更新於: 2021年10月26日

4K+ 瀏覽量

開啟您的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.