Four ways to write Hello world, or tools for creating a GUI in Python
After writing a program, you can modify it and add a graphical interface – with Python, this is easier than it seems. To program a beautiful and functional GUI, sometimes a simple knowledge of html and css is enough.
Below is a selection of some tools for creating interfaces in Python. Bookmark the article and suggest your options in the comments!
Greeting! My name is Vlad and I have been writing in Python for over five years. I managed to try a lot of things – from Olympiad programming and solving research tasks to BackEnd development and RPA.
I can say unequivocally: if not only you work with the program, but also, for example, your colleagues, you need to make an interface for it. At the same time, it does not matter what task she solves. Therefore, I have collected a selection of tools for creating GUIs in Python and mini-instructions for working with them.
If you are interested in such a format, write what topic can be analyzed in the future. For the most interesting idea, we will send a plush tirex and other Selectel merch.
Contents
Tkinter
Probably every snake charmer has tried to work with Tkinter. For me, it was one of those libraries that started my introduction to the possibilities of Python.
Tkinter is one of the most famous modules for programming interfaces for Windows, Linux and Mac.
Advantages of the module:
- Simple installation. It is enough to install the module and import it into the program.
- Intuitive logic Everything is simple: call the object, create and add graphic elements.
Once upon a time, I wrote a program for local accountants that compared spreadsheets. It was necessary to make an interface so that customers could work with the program independently. And for this task, Tkinter was more than enough.
With the help of this module, you can make simple desktop programs. Based on my experience, Tkinter is great for beginning researchers who are bored with software like LabVIEW and want to write their own interface for calculations.
Example of work
To create a simple button that will display Hello world when pressed, it is enough to import the module, initialize the frame and add the appropriate object.
# импортируем модуль
from tkinter import *
def hello_world():
print("Hello world")
# создаем окно main
main = Tk()
# добавляем кнопку, настраиваем ее форму и цвет
# при нажатии сработает функция hello world
btn = Button(main, width=20,
height=7, text="Кнопка",
bg="white", fg="black",
command=hello_world)
btn.pack()
main.mainloop()
An example of a program on Tkinter, a simple button.
What should be considered
Tkinter is both a simple and complex tool for creating GUIs. Thus, difficulties arise when building “large-scale” interfaces: you can only work with code, and the mechanics of placing elements are not always obvious.
You can use the grid and geometry managers place and pack. Learning these tools is probably the hardest part of diving into Tkinter. Especially if you want to learn how to make responsive interfaces.
Ways to place elements in Tkinter.
Eel
You know html and css – use the Eel module. With its help, you can create web interfaces as separate applications. A prime example written in Electron, the ancestor of Eel, is Discord.
With the help of the Eel library, you can not only write a beautiful interface in html and css, but also dynamic animations based on JavaScript.
Example of work
Step 1.
First, you need to create an html document and add markup to it.
<head>
<meta charset="UTF-8">
<!-- добавляем название окна программы -->
<title>T-Rex</title>
<script src="https://habr.com/ru/companies/selectel/articles/750146/eel.js"></script>
</head>
<body>
<!-- выводим текст -->
<h1>Hello, T-Rex!</h1>
</body>
project/main.html
Step 2 Next, you need to run the HTML document using Eel.
import eel
eel.init("")
eel.start("main.html", size=(700, 700))
project/start.py
Done – after launch, the program will open the html document project/main.html in the browser:
What should be considered
The module creates a GUI with the Chromium core in mind. Only you know whether this is bad for your project or not. But there could potentially be problems with optimization, RAM consumption.
However, with the help of Eel, you can gain flexibility and simplify the development of complex adaptive applications – it is enough to use the good old flexbox. For example, if you need an application for viewing large spreadsheets, you can simply create a GUI based on Eel with the Google Sheets html frame.
At the same time, the user of the program, as it were, performs the role of a client and a server at the same time. Eel launches localhost:8000
and opens a browser – Chrome or Windows Edge – with a flag --app
, which allows you to set the default window size. The project can be compiled with PyInstaller or Auto PY to EXE and distributed as an executable file.
Interested in Python? We have collected the most interesting and popular requests from developers in one file! The link contains materials on game development, machine learning, programming of microcontrollers and graphical interfaces.
PyQt
Until now, we have considered the modules from which you can write the interface. But there is a more convenient (IMHO) and professional GUI creation tool — a library
PyQt
. Its advantage is compatibility with the Qt Designer builder, which provides a set of ready-made interface elements.
Qt Designereditor interface.
Example of work
To create an interface, it is enough to install PyQt through the pip package manager, sketch the QtDesigner interface, save it in .ui format and connect it to the program.
Let’s look at an example of how to write a simple interface and handle pushing a button (pushButton):
# подключаем необходимые пакеты
from PyQt6 import uic
from PyQt6.Widgets import QApplications
# эта функция срабатывает при нажатии кнопки
def hello_world():
print("Hello world")
# подключаем файл, полученный в QtDesigner
Form, Window = uic.loaduiType("interface.ui")
app = QApplication([])
window, form = Window(), Form()
form.setupUi(window)
window.show()
# настраиваем сценарий для элемента pushButton
form.pushButton.clicked.connect(hello_world)
# запускаем окно программы
app.exec()
After launching and clicking the button, the program will print Hello world – check it yourself. But these advantages of PyQt are revealed when developing complex interfaces.
In my practice, I used PyQt for cross-platform GUIs for automation tasks. A clear example is the converter of articles from Google documents to Habr, which I talked about in the previous article.
What should be considered
Qt’s built-ins were almost always enough. However, sometimes you may encounter objects that do not work correctly. For example – QTextBrowser, which cannot read complex html code like blockquote.
The main advantage of PyQt is the detailed documentation, in which all interface elements, their parameters and data types are well described. Believe me, you will need the reference materials more than once to work with this framework. But if you prefer the video format, I can safely recommend Oleg Shpagin’s lessons.
PyTouchBar
Since 2016, some MacBook Pro models have an OLED touch panel. In fact, it simply replaces the function keys. But it is a bit more interesting: you can display bookmarks and even media elements on the touchbar.
With the help of the PyTouchBar library, you can make your interface for the touchbar and even create a game without diving into the jungle of drivers and development in Swift. We talked about how to do it in detail in a separate article.
Game with a dinosaur Google on touchbars.
Useful materials for developers