tkinter设置子窗口在主窗口的正中间
时间: 2023-10-19 10:53:19 浏览: 39
要将子窗口设置在主窗口的正中间,您可以使用`place()`方法来设置子窗口的位置。以下是一个示例代码:
```python
import tkinter as tk
def create_child_window():
child_window = tk.Toplevel(root)
child_window.title("子窗口")
child_window.geometry("200x200")
# 获取主窗口的尺寸
root_width = root.winfo_width()
root_height = root.winfo_height()
# 获取子窗口的尺寸
child_width = child_window.winfo_reqwidth()
child_height = child_window.winfo_reqheight()
# 计算子窗口在主窗口中的位置
x = (root_width - child_width) // 2
y = (root_height - child_height) // 2
# 设置子窗口的位置
child_window.geometry(f"+{x}+{y}")
root = tk.Tk()
root.title("主窗口")
root.geometry("400x400")
# 创建按钮来打开子窗口
button = tk.Button(root, text="打开子窗口", command=create_child_window)
button.pack(pady=20)
root.mainloop()
```
在上述代码中,我们首先创建了一个名为`create_child_window`的函数,该函数用于创建子窗口。在这个函数中,我们使用`Toplevel`类创建了一个子窗口`child_window`,并设置了其标题和尺寸。
然后,我们通过`root.winfo_width()`和`root.winfo_height()`方法获取主窗口的宽度和高度。接着,我们通过`child_window.winfo_reqwidth()`和`child_window.winfo_reqheight()`方法获取子窗口的建议宽度和高度。
然后,我们使用简单的数学计算,将子窗口的左上角位置计算为`(x, y)`,使其位于主窗口的正中间。最后,我们使用`geometry()`方法将子窗口放置在计算得到的位置。
通过点击按钮,子窗口将显示在主窗口的正中间位置。请注意,如果您调整了主窗口的大小,子窗口将保持在主窗口的中心位置。