How to center a window on the screen in tkinter?

Member

by domenico , in category: Third Party Scripts , 25 days ago

How to center a window on the screen in tkinter?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 24 days ago

@domenico 

To center a window on the screen in Tkinter, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
import tkinter as tk

def center_window(root, width, height):
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    x = (screen_width - width) // 2
    y = (screen_height - height) // 2

    root.geometry(f'{width}x{height}+{x}+{y}')

root = tk.Tk()
root.title('Centered Window')
center_window(root, 600, 400)

root.mainloop()


This code creates a function center_window that takes the root window object, the width, and the height of the window as parameters. It calculates the center coordinates based on the screen size and sets the geometry of the window accordingly. Finally, it calls the function with the root window object and the desired width and height to center the window on the screen.