Build Your 1st Python GUI With Tkinter
Step-by-Step tutorial to build your first GUI with Python library “Tkinter”.
Why Python?
Python, the most favorite language among beginners, is known for its simplicity and its clean and concise way of implementing things. Despite the hype around machine learning, Python has done enough to conquer the web application domain as well.
Tkinter?
Tkinter is the standard GUI library for Python. Python when combined with Tkinter provides a fast and easy way to create GUI applications. Tkinter provides a powerful object-oriented interface to the Ti GUI toolkit.
Tkinter is a compelling choice for building GUI applications in Python, especially for applications where a modern shine is unnecessary, and the top priority is to build something that’s functional and cross-platform quickly.
Should I use tkinter?
First of all, if you write Python code and are interested in Graphical interfaces, I think you should take some time learning tkinter, even if you decide later to go back to text mode stuff or to learn or use some other GUI toolkit. Think about it as another tool in your backpack. You may choose to use it when the right time comes.
Now, because not everything is perfect, let’s do a quick summary of some of tkinter’s strengths and weaknesses:
PROS:
- It’s simple to learn and use
- Highly portable
- Brevity
- Cross platform
- Extensibility
- Maturity: The core is developed and stable
CONS:
- Limited widget set (e.g., no date picker, no webview)
- No UI designer.
- It’s not as fast as a native Swift or C++ GUI
Note: Tkinter comes pre-installed with Python3, and you need not bother about installing it.
Now, let’s build a very simple GUI with the help of Tkinter and understand it with the help of a flow diagram.
Creating a GUI application using Tkinter is an easy task. All you need to do is perform the following steps −
- Import the Tkinter module.
- Create the GUI application main window.
- Add one or more of the above-mentioned widgets to the GUI application.
- Enter the main event loop to take action against each event triggered by the user.
Every GUI apps include two steps.
- Creating a User Interface
- Adding functionalities to the GUI
Step1 : First, you import the key component, i.e., the Tkinter module.
Step2 : As a next step, you initialize the window manager with the Tk() method and assign it to a variable. This method creates a blank window with close, maximize, and minimize buttons on the top as a usual GUI should have.
Step3: Then, you will define the size of the window in width(312) and height(324) using the ‘geometry’ method.
Step4: Then as an optional step, you will Rename the title of the window as you like with window.title(title_of_the_window)
Step5: Let’s now define all the required functions for the calculator to work.
First function is the “input_number” which will continuously update the input field whenever a number is entered or any button is pressed it will act as a button click update.
Second function is ‘clear_input_field’ clears the input field or previous calculations using the button “Clear”
Third function is “evaluate” which will calculate the expression present in input field.
Once all the functions are defined then comes the main section where you will start defining the structure of the calculator inside the GUI.
Widgets
Widgets are similar in spirit to elements in HTML. You will find different types of widgets for different types of elements in the Tkinter. They are standard GUI elements and provide the user with controls like buttons, text, menus, and text boxes.
- Button: Button widget has a property for switching on/off. When a user clicks the button, an event is triggered in the Tkinter.
Syntax: button_widget = tk.Button(widget, option=placeholder) where widget is the argument for the parent window/frame while option is a placeholder that can have various values like foreground & background color, font, command (for function call), image, height, and width of button.
- Entry: Entry widget is used to create input fields or to get input text from the user within the GUI.
Syntax: entry_widget = tk.Entry(widget, option=placeholder) where widget is the parameter for the parent window/frame while option is a placeholder that can have various values like border-width, background color, width & height of button etc.
- Frame: Frame is used as containers in the Tkinter for grouping and adequately organizing the widgets.
Syntax: frame_widget = tk.Frame(widget, option=placeholder) where widget is the parameter for the parent window/frame while option is a placeholder that can have various values like border-width, height & width of widget, highlightcolor (color when widget has to be focused).
StringVar() is the variable class. We create an instance of this class.
The first thing is to create a frame for the input field.
Create the text entry box for showing the expression . grid method is used for placing the widgets at respective positions in table like structure .
Once you have the input field defined then you need a separate frame which will incorporate all the buttons inside it below the ‘input field’.
The first row will comprise of the buttons ‘Clear ©’ and ‘Divide (/)’
The second row will comprise of the buttons ‘7’, ‘8’, ‘9’ and ‘Multiply (*)
The third row will comprise of the buttons ‘4’, ‘5’, ‘6’ and ‘Subtract (-)
The fourth row will comprise of the buttons ‘1’, ‘2’, ‘3’ and ‘Addition (+)
Finally, the fifth row will comprise of the buttons ‘0’, ‘Decimal (.)’, and ‘Equal To (=)
Finally, as the last step, you use the mainloop() method to display the window until you manually close it. It runs an infinite loop in the backend.
If you have gotten this far into the blog give yourself a pat on the back because guess what? You’re awesome. This is just the starting point
There is still a lot to cover, and you might want to explore the concept of Classes in Tkinter for which you can refer to this documentation.
Please feel free to ask any questions related to this tutorial in the comments section below.
Did you like what you read?
Hold the “clap” button and give me a shoutout on linkedin.
Как сделать кнопку python
Одним из наиболее используемых компонентов в графических программах является кнопка. В tkinter кнопки представлены классом Button . Основные параметры виджета Button:
command : функция, которая вызывается при нажатии на кнопку
compund : устанавливает расположение картинки и текста относительно друг друга
cursor : курсор указателя мыши при наведении на метку
image : ссылка на изображение, которое отображается на метке
pading : отступы от границ вилжета до его текста
state : состояние кнопки
text : устанавливает текст метки
textvariable : устанавливает привязку к элементу StringVar
underline : указывает на номер символа в тексте кнопки, который подчеркивается. По умолчанию значение -1, то есть никакой символ не подчеркивается
width : ширина виджета
Добавим в окно обычную кнопку из пакета ttk:
Для создания кнопки используется конструктор Button() . В этом конструкторе с помощью параметра text можно установить текст кнопки.
Чтобы разместить виджет в контейнере (главном окне), у него вызывается метод pack() . На ОС Windows мы получим следующую кнопку:
Конструктор Button определяет различные параметры, которые позволяют настроить поведение и внешний вид кнопки. Однако конкретный набор параметров зависит от того, используем ли мы кнопки из пакета tkinter или из пакета tkinter.ttk.
Обработка нажатия на кнопку
Для обработки нажатия на кнопку необходимо установить в конструкторе параметр command , присвоив ему ссылку на функцию, которая будет срабатывать при нажатии:
Здесь в качестве обработчика нажатия устанавливается функция click_button. В этой функции изменяется глобальная переменная clicks, которая хранит число кликов. Кроме того, изменяем текст кнопки, чтобы визуально было видно сколько нажатий произведено. Таким образом, при каждом нажатии кнопки будет срабатывать функция click_button, и количество кликов будет увеличиваться:

Отключение кнопки
Для ttk-кнопки мы можем установить отключенное состояние с помощью метода state() , передав ему значение «disabled». С такой кнопкой пользователь не сможет взаимодействовать:
При этом в метод state мы можем передать набор состояний, поэтому значение «disabled» передается внутри списка.
# Button — кнопка
Для создания кнопки используется конструктор Button() . В этом конструкторе с помощью параметра text можно установить текст кнопки:
Чтобы сделать элемент видимым, у него вызывается метод pack() . В итоге вверху окна будет красоваться кнопка:
Каждый виджет, в том числе кнопка, имеет ряд атрибутов, которые влияют на ее визуализацию и которые мы можем настроить через конструктор:
Параметры bg — background и fg — foreground получают значение цвета. Результат выполнения:
# Параметры виджета
Всего же конструктор Button может принимать следующие параметры:
Параметр master представляет ссылку на родительский контейнер. В случае выше это могло бы быть само графическое окно, и мы могли написать:
Однако если в коде создается одно окно, то кнопка и любой другой элемент уже по умолчанию размещаются в этом окне. Поэтому первый параметр можно опустить, как в примерах выше. Если бы у нас в коде создавалось бы несколько окон, тогда мы могли бы передать в Button(root) ссылку на нужное окно.
Второй параметр options представляет набор параметров, которые мы можем установить по их имени:
- activebackground : цвет элемента, когда он находится в нажатом состоянии;
- activefontground : цвет текста элемента, когда он в нажатом состоянии;
- bd : толщина границы (по умолчанию 2);
- bg/background : фоновый цвет;
- fg/fontground : цвет текста;
- font : шрифт текста, например, font= «Arial 14» — шрифт Arial высотой 14px , или font=(«Verdana», 13, «bold») — шрифт Verdana высотой 13px с выделением жирным;
- height : высота элемента;
- highlightcolor : цвет элемента, когда она в фокусе;
- image : изображение на элементе;
- justify : устанавливает выравнивание текста. Значение LEFT выравнивает текст по левому краю, CENTER — по центру, RIGHT — по правому краю;
- padx : отступ от границ элемента до ее текста справа и слева;
- pady : отступ от границ элемента до ее текста сверху и снизу;
- relief : определяет тип границы, может принимать значения SUNKEN, RAISED, GROOVE, RIDGE;
- state : устанавливает состояние элемента, может принимать значения DISABLED, ACTIVE, NORMAL (по умолчанию);
- text : устанавливает текст элемента;
- textvariable : устанавливает привязку к элементу StringVar ;
- underline : указывает на номер символа в тексте элемента, который подчеркивается. По умолчанию значение -1, то есть никакой символ не подчеркивается;
- width : ширина элемента;
- wraplength : при положительном значении строки текста будут переносится для вмещения в пространство элемента.
# Упражнения
Имена переменным нужно задавать корректно: состоят из двух слов (или более), отражающих суть содержания объекта, слова соединяются нижним подчеркиванием.
Button¶
Let’s start with a simple example of creating a button which displays some text.
A one-button program¶
First we import the tkinter module and give it the shorter name tk :
Then we create a Tk root object which represents the window and will be the parent for all the other widgets:
Then we create a button object which has root as parent, and to which we give the text Hello world. This object calls the method pack() which makes the button visible in the window. Finally root calls the mainloop() method to start the program:
Convert feet to meters¶
Now let’s create a real application which does something useful. The following program has an input entry field, a button and an output label. When you press the button (or hit the return key) it converts feet to meters.
After importing the classic Tk module as tk we create the root object and set a descriptive window title:
Two of the widgets, the entry widget and the label widget, have special StringVar variables:
Now it’s time to create the three widgets:
- an entry widget with the text variable feet
- a button widget with the command function calculate
- a label widget with the text variable meters
All three widgets are placed with the pack() method:
Finally we bind the calculate function also to the Return key and start the main loop:
The conversion is done by calling the calculate function which gets the feet value from the StringVar feet, converts the value to meters and sets the StringVar meters. We enclose the calculation inside a try-except statement to account for value errors, in case the input string is not numeric.
Concepts¶
To understand Tk you need to understand:
- widgets
- geometry management
- events
Widgets are the things you can see on the screen, for example a label, an entry field or a button. Later you will see checkboxes, radiobuttons, and listboxes. Widgets are sometimes referred to as controls.
Widgets are objects, instances of classes. In the example above we had the following 2-level hierarchy:
- root (Tk)
- entry (Entry class)
- button (Button class)
- label (Label class)
When you create a widget, you must pass its parent as the first argument. Whether you save the object under a variable is up to you. It depends if you need to refer to it later on. Because it is inserted into the widget hierarchy, it won’t be garbage collected.
Just creating the widget does not yet display it in the window. You need to make a call to a geometry manager.
Event bindings¶
Each widget in Tk can have event bindings. In the following example we bind a function to these events:
- enter the widget
- leave the widget
- click the mouse button
Tk expects an event callback function which has an event object as its first argument. Here we define a lambda function with an event argument e , but we do not use it here.
Event handlers can be set up for:
- the individual widget
- a class of widgets
- the toplevel window
Frame¶
The frame widget displays just a rectangle. It primarily is used as a container for other widgets. A frame has these common options:
- padding — extra space inside the frame
- borderwidth
- relief (flat, raised, sunken, solid, ridge, grove)
- width
- height
The example below shows the 6 different relief types and uses a borderwidth of 5.

Label¶
The label widget displays a static text, for example the text next to an entry. User do normally not interact with a label.
Common options are:
- text — a static text
- textvariable — a dynamic text from a variable
- image — an image to be displayed
- compound — center, top, bottom, left, right (text position in in relation to image)
- justifiy — left, center, right
- wraplength — linelength for long labels
The following example shows a label with a static text and another with a dynamic text. If both are defined, the dynamic text will have precedence. The font keyword takes a string with the font family and font size. The foreground keyword takes a color string.

Labels also accept the relief keyword.

Button¶
Buttons have a command keyword which allows to specify a function. This function is called, but without an argument. We can use the lambda function to create a function on the fly and provide an argument.