Make Desktop Application with Python part 1

Basics of PyQT

Posted by Afsal on 03-Feb-2023

Hi Pythonistas!

Today we are starting a series of posts. We will learn how to make desktop applications using python. In this post, we are learning the basic layout for desktop applications. Ultimately, we will learn how to make a working desktop application with python. Let us jump into the code.

We are using PyQt5 for this  

Installation

 pip install pyqt5

Complete Code

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel

def main():
   app = QApplication(sys.argv)
   window = QWidget()
   window.setGeometry(0, 0, 200, 200)
   text_widget = QLabel(window)
   text_widget.setText("Hello Parseltongues ....")
   text_widget.move(20,90)
   window.setWindowTitle("First App")
   window.show()
   app.exec()
   sys.exit()

if __name__ == '__main__':
   main()

We can check this part by part

Create an app instance

app = QApplication(sys.argv)

For every app we need one and only one QApplication instance.

Create a parent widget and set its geometry

window = QWidget()
window.setGeometry(0, 0, 200, 200)

Every app has at least one Qwidget. Widgets are used to interact with users.

Parameters for set geometry are 

x-coordinate from users' screens top

Y-coordinate from users' screens top left

Width of window

Height of window

Here 200*200 window created a the top left of window

Create text widget

text_widget = QLabel(window)

Creating a label widget, as a child of previous widget

Setting text widget and placing in window

text_widget.setText("Hello Parseltongues ....")

text_widget.move(20,90)

setText method is used to set the text to Qlabel. The move function is used to place 20px from the left and 90 from the top of the parent window

Set the title for the window

window.setWindowTitle("First App")

Show parent widget

window.show()

By default parent widget will not display we have to explicitly call the show function.

Start the event loop

app.exec()

This will start the event loop program wait here until the app is closed

Exit the program

sys.exit()

Output

Hope you have learned basics of pyqt from this post. In the next post, we will learn how to handle events, and take inputs from users,s, etc. Please share your valuable suggestion with afsal@parseltongue.co.in