python logo

pyqt5 button


Python hosting: Host, run, and code Python in the cloud!

PyQt5 supports buttons using the QPushButton class. This class is inside the PyQt5.QtWidgets group. The button can be created by calling the constructor QPushButton with the text to display as parameter.

Related course:

Introduction
To use buttons with a PyQt5 application, we need to update our import line:


from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot

In the initUI() method, add these lines of code:


button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)

QPushButton creates the widget, the first argument is text on the button.
The method setToolTip shows the message when the user points the mouse on the button.
Finally the button is moved to the coordinates x=100,y=70.
We need to create a method for a button click:


@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

Add connect the method to the click with:


button.clicked.connect(self.on_click)

Final PyQt5 button code:


import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)
button.clicked.connect(self.on_click)

self.show()

@pyqtSlot()
def on_click(self):
print('PyQt5 button click')

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

If you are new to programming Python PyQt, I highly recommend this book.

pyqt5-button

Screenshot of PyQt5 button example above.

Download PyQT5 Examples

BackNext





Leave a Reply:




Mrunal tawake Tue, 12 Jan 2021

How to connect more than one function to single push button?

Frank Tue, 12 Jan 2021

Buttons have one call back function. If you want to call multiple functions, you can do it inside the callback function. That means call another function inside the on_click function. You may be able to add another clicked.connect connect call, but I recmomend calling any functions you want to call in the on_click() function.

juerg maier 2021-05-02T12:28:40.449Z

Hi
Thanks for this example.
I have tried to create a test case to verify that the button wiring is working. With the help of a stackoverflow member this worked for me. May be worth to add a link?
https://stackoverflow.com/questions/67345474/extend-generated-testapp-to-verify-pyqt5-button-click
Regards, Jurg