BarricadeX75
BarricadeX75

Reputation: 106

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?

Upvotes: 1

Views: 1785

Answers (1)

acw1668
acw1668

Reputation: 47183

When those winfo_width() and winfo_height() are executed, those windows' layout have not yet confirmed, so you may get the size 1x1. 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()

Upvotes: 2

Related Questions