A_Matar
A_Matar

Reputation: 2320

Tkinter: how to fix the window opening position while letting the width and height wrap the content

I want to my Tkinter window to open at the center of the screen while not having to enter the width and height of the screen myself. I have gone through this great answer but it requires specifying the dimensions of the window.

Instead of this enter image description here

I want to get a result like this: enter image description here

Upvotes: 2

Views: 1805

Answers (1)

falsetru
falsetru

Reputation: 369064

You can use winfo_width/winfo_height (or winfo_reqwidth, winfo_reqheight) to get the window size.

def center_window(win):
    # win.update_idletasks()
    screen_width = win.winfo_screenwidth()
    screen_height = win.winfo_screenheight()
    width = win.winfo_reqwidth()
    height = win.winfo_reqheight()

    x = screen_width / 2 - width / 2
    y = screen_height / 2 - height / 2
    root.geometry('%dx%d+%d+%d' % (width, height, x, y))

used winfo_reqwidth, winfo_reqheight in case the window is not fully set up.

or you can call update_idletasks before call winfo_width / winfo_height to carry out geometry management.

Upvotes: 4

Related Questions