1 - Créer un Bouton PyQt5 avec la classe QPusButton
Pour créer un bouton de commande du type QPusButton, il suffit d'instancier la classe QPusButton:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton app = QApplication(sys.argv) win = QWidget() win.setGeometry(100 , 100 , 500 , 300) # create a QPusButton q_btn = QPushButton(win) q_btn.setText("This is a QPusButton ! ") q_btn.setGeometry(100 , 100 , 200 , 50) win.show() app.exec_() |
2 - Associer une action à un bouton QPushButton PyQt5
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton # create a button action def action(): print("Why you clicked the button !") app = QApplication(sys.argv) win = QWidget() win.setGeometry(100 , 100 , 500 , 300) # create a QPusButton q_btn = QPushButton(win) q_btn.setText("This is a QPusButton ! ") q_btn.setGeometry(100 , 100 , 200 , 50) # bind an action to the button q_btn.clicked.connect(action) win.show() app.exec_() |
Ce qui affiche à l'écran une fenêtre avec un bouton de commande et en cliquant sur ce dernier, on aperçoit l'affichage à l'écran du message:
Why you clicked the button !
3 - QPushButton PyQt5 selon l'approche objet Python
3.1 - Créer un QPushButton selon l'approche objet Python
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 |
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton class Window(QWidget): def __init__(self , window): super().__init__() self.window = window def build(self): self.window.setWindowTitle("Window With QPusButton !") self.window.setGeometry(100 , 100 , 400 , 300) # create a QPushButton self.q_btn = QPushButton(self.window) self.q_btn.setText("This is a QPushButton from object approach !") self.q_btn.setGeometry(50 , 50, 300 , 35) if __name__ == "__main__": app = QApplication(sys.argv) win = QWidget() myWin = Window(win) myWin.build() win.show() app.exec_() |
3.2 - Associer une action à un QPushButton selon l'approche objet Python
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 |
import sys from PyQt5.QtWidgets import QApplication, QWidget, QPushButton class Window(QWidget): def __init__(self , window): super().__init__() self.window = window def action(self): print("Why you clicked the button !") def build(self): self.window.setWindowTitle("Window With QPusButton !") self.window.setGeometry(100 , 100 , 500 , 300) # create a QPushButton self.q_btn = QPushButton(self.window) self.q_btn.setText("This is a QPushButton from object approach !") self.q_btn.setGeometry(100 , 100 , 250 , 35) self.q_btn.clicked.connect(self.action) if __name__ == "__main__": app = QApplication(sys.argv) win = QWidget() myWin = Window(win) myWin.build() win.show() app.exec_() |
Younes Derfoufi
CRMEF OUJDA