PyQt5 window

If you do not have PyQT5 installed, you should install it first. In a terminal you can type:

sudo apt-get install python3-pyqt5

If you are on a Windows or Mac computer, you can download PyQT5 from: https://www.riverbankcomputing.com/software/pyqt/download5

PyQt5 window

You can create a PyQT5 window using the code below:

import sys
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon

class App(QWidget):

def __init__(self): super().__init__() self.title = 'PyQt5 simple window - pythonspot.com' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.show() if __name__ == '__main__': app = QApplication(sys.argv) ex = App() sys.exit(app.exec_())

We set the window size using the setGeometry(left,top,width,height) method. The window title is set using setWindowTitle(title). Finally show() is called to display the window.

Run with:

python3 window.py

pyqt5-window

The output should look similar to the screenshot above (depending on your operating system).

Center the window on the screen

By default the window opens at the coordinates given to setGeometry. To center the window on your monitor screen, calculate the center point:

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

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'Center PyQt5 window'
        self.width = 450
        self.height = 300
        self.initUI()
        
    def initUI(self):
        self.setWindowTitle(self.title)
        self.resize(self.width, self.height)
        self.center()
        self.show()
        
    def center(self):
        # Geometry of the main window
        qr = self.frameGeometry()
        # Center point of screen
        cp = QDesktopWidget().availableGeometry().center()
        # Move rectangle center to screen center
        qr.moveCenter(cp)
        # Top left of rectangle becomes top left of window
        self.move(qr.topLeft())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

The method QDesktopWidget().availableGeometry() finds your monitor screen size and moves the window to the middle.

PyQt5 center window on screen example output

Set a window icon

To add a custom icon to the top corner of your window and taskbar, use the setWindowIcon() method:

from PyQt5.QtGui import QIcon

self.setWindowIcon(QIcon('icon.png'))

Put your icon file in the same folder as your Python script.

Download PyQT5 Code

Next ⚡ Practice with PyChallenge