How to place toplevel window in center of parent window

Question:

I am trying to place a toplevel window in the center of its parent window. I tried

window = Tk()
top = Toplevel(window)
x = window.winfo_x() + window.winfo_width() // 2 - top.winfo_width() // 2
y = window.winfo_y() + window.winfo_height() // 2 - top.winfo_height() // 2
top.geometry(f"+{x}+{y}")

But it seems that it’s ignoring the - top.winfo_width() // 2 and - top.winfo_height // 2 parts.
How can I fix this?

Asked By: BarricadeX75

||

Answers:

When those winfo_width() and winfo_height() are executed, those windows’ layout have not yet confirmed, so you may get the size 1×1. Try calling wait_visibility() (waits until the window is visible) on both windows before calling those winfo_xxxx().

from tkinter import *

window = Tk()
window.geometry('800x600')
window.wait_visibility()

top = Toplevel(window)
top.wait_visibility()

x = window.winfo_x() + window.winfo_width()//2 - top.winfo_width()//2
y = window.winfo_y() + window.winfo_height()//2 - top.winfo_height()//2
top.geometry(f"+{x}+{y}")

window.mainloop()
Answered By: acw1668
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.