DEV Community

Cover image for Desktop Window, Button & Click with Python
petercour
petercour

Posted on

Desktop Window, Button & Click with Python

Python apps don't need be command line only. You can create desktop software. In programmer language: graphical user interfaces (GUI)

So how do you make that? You need to use a module. There are several modules like tkinter, wxwidgets and pyqt. PyQt is a good choice.

If you know the object orientated programming concepts this is pretty easy. If not, check out the resources below.

So let's make a desktop application, but for the modern desktop

Example

The program below creates a desktop window with a button. If you click the button a popup will show (QMessageBox). Inside the class we set some window properties.

#!/usr/bin/python3
from PyQt5 import QtCore
from PyQt5.QtWidgets import *

class MainWindow(QMainWindow):
    def __init__(self, name, title):
        super(MainWindow, self).__init__()
        self.w = 0
        self.h = 0
        self.init_ui(name, title)

    def init_ui(self, name, title):
        self.w = 200
        self.h = 100
        self.setObjectName(name)
        self.setWindowTitle(title) 
        self.resize(self.w, self.h) 

        self.btn_clickme = QPushButton(self)
        self.btn_clickme.setGeometry(QtCore.QRect(10, 10, 100, 24))
        self.btn_clickme.setObjectName('click_me')
        self.btn_clickme.setText('clicky click!')
        self.btn_clickme.clicked.connect(self.do_something)

    def do_something(self):
        QMessageBox.information(self, 'clicked', 'clicked!')

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    n = 'Hello'
    t = 'Hello, Soaring!'
    ex = MainWindow(n, t)
    ex.show()
    sys.exit(app.exec_())

Results in:

Resources:

Top comments (0)