Home > Software design >  How to place toplevel window in center of parent window
How to place toplevel window in center of parent window

Time:08-08

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?

CodePudding user response:

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()
  • Related