How to specify where a Tkinter window opens?

xxmbabanexx picture xxmbabanexx · Feb 16, 2013 · Viewed 87.8k times · Source

How can I tell a Tkinter window where to open, based on screen dimensions? I would like it to open in the middle.

Answer

xxmbabanexx picture xxmbabanexx · Feb 16, 2013

This answer is based on Rachel's answer. Her code did not work originally, but with some tweaking I was able to fix the mistakes.

import tkinter as tk


root = tk.Tk() # create a Tk root window

w = 800 # width for the Tk root
h = 650 # height for the Tk root

# get screen width and height
ws = root.winfo_screenwidth() # width of the screen
hs = root.winfo_screenheight() # height of the screen

# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)

# set the dimensions of the screen 
# and where it is placed
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

root.mainloop() # starts the mainloop