如何在 Tkinter 中確定 Toplevel 的位置?


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

步驟 -

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

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

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

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

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

  • 最後,執行應用程式視窗的主迴圈。

示例

# 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")
win.title("Main Window")

def toplevel_position():
   print("The coordinates of Toplevel window are:", top.winfo_x(), top.winfo_y())

top = Toplevel(win, height=150, width=300)
top.title("This is the Toplevel Window")
top.attributes('-topmost', 'true')

button = ttk.Button(top, text="Get position", command=toplevel_position)

button.place(relx=0.5, rely=0.5, anchor=CENTER)

top.mainloop()

輸出

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

現在,單擊“獲取位置”按鈕,它將在控制檯上列印 Toplevel 視窗的座標。

The coordinates of Toplevel window are: 282 105

更新於: 2021年10月26日

1K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.