How to center your window with tkinter in Python

This function will help you to center the window made with tkinter on the screen

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
root.title('Centered window')

window_height = 530
window_width = 800

def center_screen():
	""" gets the coordinates of the center of the screen """
	global screen_height, screen_width, x_cordinate, y_cordinate

	screen_width = root.winfo_screenwidth()
	screen_height = root.winfo_screenheight()
        # Coordinates of the upper left corner of the window to make the window appear in the center
	x_cordinate = int((screen_width/2) - (window_width/2))
	y_cordinate = int((screen_height/2) - (window_height/2))
	root.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))

center_screen()

root.mainloop()

This script takes the width of the screen with root.winfo_screenwidth and root.winfo_screenheight

root.winfo_screenwidth()returns the width of the screen
root.winfo_screenheight()returns the heightof the screen
This two methods

Then, we get the cordinates to put the window in the middle of the screen (centered) with the difference between the half of the screen (screen_width/2) and the middle of the window width (that we defined in the code). The same for the height. This way we get the corrdinates of the upper left corner of the window that we use to position the window at the center with root.geometry that takes a string as argument in which there are:

  • width
  • height
  • x pos on the screen of the upper left corner
  • y pos on the screen of the upper left corner

root.geometry(“{}x{}+{}+{}”.format(window_width, window_height, x_cordinate, y_cordinate))

we could have used also (with the new format string):

root.geometry(f”{window_width}x{window_height}+{x_cordinate}+{y_cordinate}”)


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.