Home > Mobile >  Tkinter centering ctktoplevel window in middle of main window
Tkinter centering ctktoplevel window in middle of main window

Time:07-07

There are tons of results on centering a top level window comparative to your screen size. However, to my knowledge, there is no information out there on how to center the top level window in the center of the main window. I could hard code it but it's ugly to do and would of course not work anymore once im moving the main window to a seperate screen. So my question is, how do i center a top level window in the main window regardless of the position of the main window?

CodePudding user response:

  1. Get location of main window along with dimensions
x, y, w_main, h_main
  1. get dimensions of your top level window
w_top, h_top
  1. location of toplevel is in center of main window, so its relative position is:
x_rel = round((w_main - w_top)/2)
y_rel = round((h_main - h_top)/2)
  1. now add these relative coordinated to absolute location of main window:
x  = x_rel
y  = y_rel
  1. Place the toplevel at these coordinates
x, y
  1. repeat the whole process every time the location of main window changes, except if dimensions are fixed they can be separated out (no need to check them repeatedly)

CodePudding user response:

from tkinter import Toplevel, Button, Tk

root = Tk()

width = 960

height = 540

root.geometry("%dx%d" % (width, height))

def new_window() :
    win = Toplevel()
    win.geometry("%dx%d %d %d" % (480, 270, root.winfo_x()   width/4, root.winfo_y()   height/4))

#the geometry method can take four numbers as arguments
#first two numbers for dimensions
#second two numbers for the position of the opened window
#the position is always the top left of your window
#winfo_x and winfo_y are two methods
#they determine the current position of your window

Button(root, text = "open", command = new_window).pack()

root.mainloop()

You can test the code and make it satisfy your needs. I hope that helps !

  • Related