[英]How to make Tkinter's popup window's position at the center of the main window?
I want to know how one could make the popup window's position relative to the main window.我想知道如何使弹出窗口的 position 相对于主 window。 When I tried it the popup window goes and sits at the corner of my computer screen.当我尝试它时,弹出 window 会出现在我电脑屏幕的角落。 Here is my code.这是我的代码。
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)
First get main window position首先得到主 window position
root_x = root.winfo_rootx()
root_y = root.winfo_rooty()
next add offset to this position接下来向这个 position 添加偏移量
win_x = root_x + 300
win_y = root_y + 100
and finally use new position to move toplevel window最后使用新的 position 移动顶层 window
win.geometry(f'+{win_x}+{win_y}')
Doc effbot.org: Basic Widget Methods 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.