How to Center the Main Window on the Screen in Tkinter with Python 3

Python 3, Tkinter 8.6. GUI examples in Windows 10

When your first window loads in Tkinter it will generally appear slightly offset from the top left hand corner of the screen. This is a fairly counter intuitive location and most of the GUI driven programs that I run usually open at the center of the page or a little higher than center.

If you want a primer of window positioning, check out the following tutorial:

How Do I Change the Size and Position of the Main Window in Tkinter and Python 3

In Python 3, to put the main window in the center of the screen I use the following code:

Window Centered on the Screen in Tkinter with Python 3
Output in Windows 10

Step By Step

When we set the geometry of the position in Line 18 we need to know the dimensions of the users screen and the dimensions of the window.

Tkinter’s geometry  positions the window based on the window’s top left hand corner. To find out this position we need to halve the width and height of the screen and subtract those by half the width and height of the window.

Tkinter Center Half Screen Width Minus Half Window Width

To find out the screen and window values we use Tkinter’s winfo command that allows us to find out information about the the windows we create with Tkinter and how they are positioned in the screen.

winfo_reqwidth and winfo_reqheight

On lines 9 and 10 we create the variables for the window’s width and height.

We use win_reqheight rather than win_height because we have not set the size in the geometry yet. reqheight and reqwidht are the requested heights and width of the window. This takes into account all the sizing that might take place inside the window when we size things like labels, buttons and text boxes.

In the current example we haven’t put anything in the window so Tkinter will use it’s standard height and width of 200×200. I’ve kept the print call in there for you to check for yourself.

winfo_screenwidth and winfo_screenheight

 

On lines 13-15 , we create the position variables. Here we first get the screen width and height. We use the winfo_screenwidth and winfo_screenheight for this.

We then continue to carry out the formula to find the center point of the screen offset by half the width and height of the window. This will often calculate as a float that needs to be converted to an integer with int before it can be added to the geometry.

Adding the position to the geometry.

Finally we set the position of the window using the geometry method.

 

A little bonus: 

I often find that most programs usually open a little above center on the screen. To do this I divide the screen height by 3:

Window Positioned a Little Higher Up - Tkinter Python 3

 

Leave a Reply

Your email address will not be published. Required fields are marked *