在 Tkinter Python 中設定按鈕的位置?


有幾種方法可以透過 Tkinter 小元件放置在視窗中。Tkinter 幾何管理程式有三個方法,pack()、place()grid(),我們可透過這些方法設定小元件在應用程式視窗中的位置。每種方法都有其侷限性和用途。要設定 Tkinter 應用程式視窗中按鈕的位置,我們優先考慮使用 place(x 座標, y 座標) 方法。它採用定義小元件位置所需的 x 和 y 座標值。

示例

示例程式碼包含一個按鈕小元件,它使用 place(x, y) 方法將按鈕放置在視窗中。

# Import the Tkinter library
from tkinter import *
from tkinter import ttk
# Create an instance of Tkinter frame
win = Tk()
# Define the geometry
win.geometry("750x250")
def close_win():
   win.destroy()
# Create Buttons in the frame
button = ttk.Button(win, text="Click", command=close_win)
button.place(x=325, y=125)
#Create a Label
Label(win, text="Click the Button to Close the Window", font=('Consolas 15')).pack()
win.mainloop()

輸出

執行以上程式碼將顯示一個視窗,視窗中心位置有一個按鈕。

更新時間: 22-Apr-2021

2K+ 閱讀

啟動你的 職業

透過完成課程獲得認證

開始
廣告