Popular Posts

Saturday, March 4, 2023

PyQt Button - Event connection

Hello Python developer, hope you're good today!


Today, we will learn about PyQt button and event connection.

For button creation in your window, use 'QPushButton' class as following exercise.

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(200, 200, 400, 300)
        self.setWindowIcon(QIcon("PyQt window sample icon.png"))
       
        btn = QPushButton("Button 1", self)
       
app = QApplication(sys.argv)
window = MyWindow()
window.show()
app.exec_()


Code run result :

Can you click the "Button 1"? Yes, you can click it but threr is no action by button click.

Now, we will connect the 'Event' when we click this 'Button 1'.
Let's type and run following Python codes.

# PyQt Window Button - Event connection exercise

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

class QtWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setGeometry(200, 200, 400, 300)
        self.setWindowTitle("PyQt Button Click event exercise")
        self.setWindowIcon(QIcon("PyQt window sample icon.png"))
       
        btn = QPushButton("Button 1", self)
        btn.move(10,10)
        btn.clicked.connect(self.btn_clicked)
       
    def btn_clicked(self):
        print("Button clicked")
       
app = QApplication(sys.argv)
window = QtWindow()
window.show()
app.exec_()

Code run result : Type "Button clicked" text when you click the 'Button 1".



Can you click the 'Button 1' and see the 'Button clicked' text in your terminal or Python execution window?


That's great! Let's learn more about PyQt GUI!



Python - Web crawling exercises

Hello Python developer! How are you? Hope you've been good and had wonderful time with Python. There are 10 Python requests module exerc...