python - 如何使 Tkinter 的弹出窗口的位置在主窗口的中心?
问题描述
我想知道如何使弹出窗口相对于主窗口的位置。当我尝试它时,弹出窗口会出现在我电脑屏幕的一角。这是我的代码。
def popup_bonus(self):
win = tk.Toplevel()
win.wm_title("Error")
win.configure(bd=0, highlightthickness=0)
win.overrideredirect(1)
l = ttk.Label(win, text="Already Exists")
l.grid(row=0, column=0)
b = tk.Button(win, text="Okay", command=win.destroy)
b.grid(row=1, column=0)
解决方案
首先获取主窗口位置
root_x = root.winfo_rootx()
root_y = root.winfo_rooty()
接下来向这个位置添加偏移量
win_x = root_x + 300
win_y = root_y + 100
最后使用新位置移动顶层窗口
win.geometry(f'+{win_x}+{win_y}')
Doc effbot.org:基本小部件方法
import tkinter as tk
# --- functions ---
def on_click():
# get main window position
root_x = root.winfo_rootx()
root_y = root.winfo_rooty()
# add offset
win_x = root_x + 300
win_y = root_y + 100
win = tk.Toplevel()
# set toplevel in new position
win.geometry(f'+{win_x}+{win_y}')
button = tk.Button(win, text='OK', command=win.destroy)
button.pack()
# --- main ---
root = tk.Tk()
root.geometry('800x600') # only size
#root.geometry('+100+200') # only position
#root.geometry('800x600+100+200') # both: size and position
button = tk.Button(root, text='OK', command=on_click)
button.pack()
root.mainloop()
推荐阅读
- r - 使用 animate 包创建地图动画
- sql - 如何根据SQL中另一表的匹配字符串列更新一个表的数字列
- python-3.x - 如何右对齐打印 Python 整数列表
- html - 如何在 asp.net 中更新一个列(稍后更好地描述)
- javascript - 所有浏览器上的 CSP 错误,除了带有样式组件的基于 chrome 的浏览器
- wordpress - 使用wordpress中的参数将简码添加到自定义帖子
- python - 安装 TensorFlow 1.15
- mongodb - 如何创建 MongoDB 更新查询以更新对象数组中的某些元素
- strapi - 为什么在提供者部分下的strapi中禁用重定向URL字段
- css - 如何在 EDGE 浏览器中更改属性