如何定位 Tkinter 視窗上的按鈕?
要設定按鈕的位置,我們使用按鈕控制元件的方法 place。方法 place 採用按鈕的 x 和 y 座標。
步驟 -
匯入所需的庫並建立 tkinter 框架例項。
使用 win.geometry 方法設定框架的大小。
接下來,建立多個按鈕並將其命名為“Button-1”、“Button-2”等。
透過提供 x 和 y 座標值,使用 place 方法設定按鈕的位置。
最後,執行應用程式視窗的 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-1") button.place(x=325, y=125) button = ttk.Button(win, text="Button-2") button.place(x=325, y=175) button = ttk.Button(win, text="Button-3") button.place(x=325, y=225) #Create a Label Label(win, text="Position the Buttons", font='Consolas 15').pack() win.mainloop()
輸出
當你執行這段程式碼時,它將顯示以下視窗 -
請注意,我們在所有三個按鈕中都將 x 變數固定為 325,這就是按鈕對其的原因。你可以更改 place 方法中的 (x, y) 值來改變按鈕的位置。
廣告