如何在 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP