How To Center A Window On The Screen In Tkinter?

Tkinter provides a basic geometry manager to control the placement of widgets within a window, it doesn’t offer a built-in method to automatically center a window on the screen. However, achieving this task is relatively straightforward with a few lines of code. In this article, we’ll explore different approaches to centering a Tkinter window on the screen.

Center a Window On The Screen In Tkinter

Below are some of the ways by which we can center a window on the screen in Tkinter:

  1. Using Geometry Management
  2. Using Screen Dimensions

Using Geometry Management

Tkinter’s geometry manager allows developers to specify the size and position of widgets within a container. To center a window using this method, we’ll first calculate the screen dimensions and then set the window’s position accordingly.

Python
import tkinter as tk

def center_window(window):
    window.update_idletasks()
    width = window.winfo_width()
    height = window.winfo_height()
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = (screen_width - width) // 2
    y = (screen_height - height) // 2
    window.geometry(f"{width}x{height}+{x}+{y}")

# Example usage:
root = tk.Tk()
root.title("Centered Window")
center_window(root)
root.mainloop()

Output:

Using Screen Dimensions

Another approach is to utilize the tkinter’s winfo_screenwidth and winfo_screenheight methods directly to center the window without calculating its dimensions explicitly.

Python
import tkinter as tk

def center_window(window):
    screen_width = window.winfo_screenwidth()
    screen_height = window.winfo_screenheight()
    x = (screen_width - window.winfo_reqwidth()) // 2
    y = (screen_height - window.winfo_reqheight()) // 2
    window.geometry(f"+{x}+{y}")

# Example usage:
root = tk.Tk()
root.title("Centered Window")
center_window(root)
root.mainloop()

Output:


Contact Us