Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to place toplevel window in center of parent window

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading