How to center a Window on the Screen in Tkinter
report this ad
report this ad
report this ad
In this tutorial we will discuss how to center a Tkinter Window on the Screen!
It’s rather annoying isn’t it? When you launch your Tkinter program, and it appears somewhere in the corner of the screen. Although this might seem acceptable to you, but it certainly won’t to any end-users you may distribute your software too.
Luckily we have two methods which we will be discussing in this tutorial on how to adjust the Screen position upon startup.
Using the Geometry() Function
Often when making GUI applications with Tkinter, you may want to define a size for the Tkinter Window. Now there are many different ways of doing this, such as using a Frame with a specified size. Another popular and easy way to do so is using the Geometry() function.
The Geometry function can also be extended to adjust the initial starting point of the Window.
In the below example, we have used a couple of useful functions to determine the size of the Screen (e.g: 1920×1080) and then doing some simple calculations to determine where the top-left corner of the Tkinter Window should spawn so that it’s perfectly centered.

Tkinter eval() function
Another short and very easy way of centering the Tkinter Screen is to use the eval() function on the Tkinter instance with the appropriate parameter as shown below.
Try running the code for yourself to the see the magic unfold!
Note: I personally like the first method more, as it gives one alot of control over how things are handled, and can be further customized.
This marks the end of the How to center a Window on the Screen in Tkinter Tutorial. Any suggestions or contributions for CodersLegacy are more than welcome. Questions regarding the tutorial content can be asked in the comments section below.
Создание окна по центру и кнопка выхода в Tkinter

В этой части обучения Tkinter мы познакомим Вас с инструментом Tkinter и создадим первые программы. Целью этого руководства является ознакомление с базой инструментария Tkinter. Я использовал несколько иконок из набора Tango от Gnome project.
Содержание курса
- Создание окна по центру и кнопка выхода в Tkinter
Содержание статьи
Tkinter библиотека для создания графических интерфейсов
Tkinter – это графическая библиотека на основе Tk, которая входит в стандартную библиотеку Python. Tk является библиотекой базовых элементов графического интерфейса для языка Tcl. Tkinter реализован как оболочка Python для Tcl интерпретатора, встроенного в интерпретатор Python. Существует и несколько других популярных графических инструментов для Python. Наиболее популярными являются wxPython, PyQt5 и PyGTK.
Язык программирования Python
Python – это высокоуровневый, динамичный, объектно-ориентированный язык программирования. Он ориентирован на повышение производительности программиста и читаемости кода. Разработчиком кода является Гвидо ван Россум. Впервые язык увидел свет в 1991 году. При создании Python, автор вдохновлялся такими языками программирования как ABC, Haskell, Java, Lisp, Icon и Perl. Python является высокоуровневым, кроссплатформенным, но в то же время минималистичным языком. Одним из его основных преимуществ является отсутствие скобок и точек с запятой. Вместо этого Python использует отступы. Сегодня существует две основные ветви языка: Python 2.7 и Python 3.x.
Стоит отметить, что Python 3 нарушает обратную совместимость с предыдущими версиями языка. Его разработали для того, чтобы исправить ряд недостатков конструкции уже существующего языка, упростить и очистить его от ненужных деталей. Последней версией Python 2.x является 2.7.17, а Python 3.x – 3.8.5. Данный учебник написан на Python 2.x, равно как и большая часть кода. Мы обновили учебник под Python 3.8.
Для перехода программного обеспечения и самих разработчиков на Python 3.x потребуется какое-то время. Уже перешли все на Python 3. Сегодня Python поддерживается большим количеством добровольцев со всего мира. Напомню, что язык имеет открытый исходный код.
Python – это идеальный язык для тех людей, которые хотят научиться программировать.
Язык программирования Python поддерживает несколько стилей программирования. Он не принуждает разработчика придерживаться определенной парадигмы. Python поддерживает объектно-ориентированное и процедурное программирование. Существует и ограниченная поддержка функционального программирования.
How to center a window on the screen in Tkinter?
I’m trying to center a tkinter window. I know I can programatically get the size of the window and the size of the screen and use that to set the geometry, but I’m wondering if there’s a simpler way to center the window on the screen.
15 Answers 15
The simplest (but possibly inaccurate) method is to use tk::PlaceWindow, which takes the pathname of a toplevel window as an argument. The main window’s pathname is .
The problem
Simple solutions ignore the outermost frame with the title bar and the menu bar, which leads to a slight offset from being truly centered.
The solution
With tkinter you always want to call the update_idletasks() method
directly before retrieving any geometry, to ensure that the values returned are accurate.
There are four methods that allow us to determine the outer-frame’s dimensions.
winfo_rootx() will give us the window’s top left x coordinate, excluding the outer-frame.
winfo_x() will give us the outer-frame’s top left x coordinate.
Their difference is the outer-frame’s width.
The difference between winfo_rooty() and winfo_y() will be our title-bar / menu-bar’s height.
You set the window’s dimensions and the location with the geometry method. The first half of the geometry string is the window’s width and height excluding the outer-frame,
and the second half is the outer-frame’s top left x and y coordinates.
You see the window move
One way to prevent seeing the window move across the screen is to use .attributes(‘-alpha’, 0.0) to make the window fully transparent and then set it to 1.0 after the window has been centered. Using withdraw() or iconify() later followed by deiconify() doesn’t seem to work well, for this purpose, on Windows 7. I use deiconify() as a trick to activate the window.
Making it optional
You might want to consider providing the user with an option to center the window, and not center by default; otherwise, your code can interfere with the window manager’s functions. For example, xfwm4 has smart placement, which places windows side by side until the screen is full. It can also be set to center all windows, in which case you won’t have the problem of seeing the window move (as addressed above).
Multiple monitors
If the multi-monitor scenario concerns you, then you can either look into the screeninfo project, or look into what you can accomplish with Qt (PySide6) or GTK (PyGObject), and then use one of those toolkits instead of tkinter. Combining GUI toolkits results in an unreasonably large dependency.
How to Center the Main Window on the Screen in Tkinter with Python 3
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 centre of the page or a little higher than the center.
If you want a primer of window positioning, check out the following tutorial:
In Python 3, to put the main window in the center of the screen I use the following code:
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 user’s 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.
To find out the screen and window values we use Tkinter’s winfo command that allows us to find out information about 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 its 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 centre 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 centre on the screen. To do this I divide the screen height by 3:
Want to learn how to automate your daily admin at work with Python? Udemy has some great Python automation courses that will help you learn how to automate your tasks so you can focus on what really matters.
Got a more specific problem you need help with, but don’t have the time to develop the skills? Fiverr ’s your best bet to find a skilled professional to solve your problem quickly and cheaply . *
*The above affiliate links have been carefully researched to get you to what you specifically need. If you decide to click on one of these links it will cost you just the same as going to the site. If you decide to sign up, I just get a little pocket money to help pay for the costs of running this website.