Buttons (QPushButton) can be added to any window. The QPushButton class has the method setText() for its label and move(x,y) for the position.

In this article you can see how a button can be added to a window, and how you can connect methods to it.

Related Course:
PyQt Desktop Apps with Python
icon

PyQt Button Example

Signals and slots

You can create a button with a few lines of code:

1
2
3
button1 = QPushButton(widget)
button1.setText("Button1")
button1.move(64,32)

Then connect it to a method with:

1
button1.clicked.connect(button1_clicked)

The receiving method is called a slot, the clicked.connect (if the button is clicked) is called a signal.

1
2
def button1_clicked():
print("Button 1 clicked")

Button example

Run the code below to see 2 buttons in a window. You can click either one of the buttons and their connected methods will be called.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

def window():
app = QApplication(sys.argv)
widget = QWidget()

button1 = QPushButton(widget)
button1.setText("Button1")
button1.move(64,32)
button1.clicked.connect(button1_clicked)

button2 = QPushButton(widget)
button2.setText("Button2")
button2.move(64,64)
button2.clicked.connect(button2_clicked)

widget.setGeometry(50,50,320,200)
widget.setWindowTitle("PyQt5 Button Click Example")
widget.show()
sys.exit(app.exec_())


def button1_clicked():
print("Button 1 clicked")

def button2_clicked():
print("Button 2 clicked")

if __name__ == '__main__':
window()