Search code examples
pythontkintercustomtkinter

Tkinter centering ctktoplevel window in middle of main window


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?


Solution

  • 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 a string argument
    #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 !