Search code examples
tkinterwidgettoplevel

How to put a window and a toplevel side by side in Tkinter?


from tkinter import *

def graphical_grid_init():
    root = Tk()
    root.title("2048")
    w = Toplevel(root)
    w.title("2048")
    
    root.mainloop()

graphical_grid_init()

This code spawns 2 windows but I want them to be side by side, and apparently i can't call the fonction "grid" after my toplevel window (for example : w.grid(column=1)) to place it as it is not a widget, however in our subject they ask us to do so.
How could i place my windows side-by-side ? Thanks


Solution

  • As Cool Cloud said,

    w.geometry(f'+{px}+{px}') is what you need to use, keep in mind, you will have to come up with something dynamic, because your pixels wont be same as someone elses.

    So here is a solution

    from tkinter import *
    
    
    def graphical_grid_init():
        root = Tk()
        root.title("2048")
        width,height = 200,100 # with and height of the root window
        w = Toplevel(root)
        w.title("2048")
        w_width,w_height = 200,100 # width and height of the toplevel window
    
        setwinwidth = ((root.winfo_screenwidth()-width)//2) - width//2
        setwinheight = (root.winfo_screenheight()-height)//2
        settopwidth = ((root.winfo_screenwidth()-w_width)//2) + w_width//2
        settopheight = (root.winfo_screenheight()-w_height)//2
    
        root.geometry(f"{width}x{height}+{setwinwidth}+{setwinheight}")
        w.geometry(f"{w_width}x{w_height}+{settopwidth}+{settopheight}")
    
        root.mainloop()
    
    graphical_grid_init()
    

    here, I get the actual width and height of the user's screen using the methods, winfo_screenwidth and winfo_screenheight. Then I use these sizes as well as the sizes provided for the two windows to be displayed, to dynamicaly resize and position the windows on the screen.