2

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

Community
  • 1
  • 1
A_Matar
  • 2,210
  • 3
  • 31
  • 53

1 Answers1

3

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • This doesn't give me exactly what I want. It gives me this https://ibb.co/nmWbvk (check the updated question for screenshots that further explain what I want. – A_Matar May 12 '17 at 08:14
  • 1
    @A_Matar Try and call `root.update()` right before the first call to the `winfo` methods. There's an issue about widget height and width and how they're stored, for instance: http://stackoverflow.com/q/13327659/7051394 – Right leg May 12 '17 at 08:18
  • @Rightleg Yeah it worked, if you may edit the original answer, so that I can mark it accepted – A_Matar May 12 '17 at 08:21
  • 1
    @A_Matar, Added `win.update_idletasks()` line to the code in the answer and mentioned about update_idletasks. – falsetru May 12 '17 at 09:09