Get the App
SLTechnology News&Howtos  ›  Development  › 

Python programming PyQt5 how to create buttons and trigger Click events

Shulou Source: shulou.com Published: 2022-06-02 21:45:14 09月30日 Update

This article mainly introduces "python programming PyQt5 create button and trigger click event method tutorial". In daily operation, I believe many people have doubts about the method tutorial of creating button and triggering click event in python programming PyQt5. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "python programming PyQt5 create button and trigger click event method tutorial". Next, please follow the editor to study!

The code is as follows:

#-*-coding:utf-8-*-import sysfrom PyQt5.QtWidgets import QMainWindow, QApplication, QPushButtonclass MainWindow (QMainWindow): def _ _ init__ (self, parent=None): super (MainWindow, self). _ _ init__ (parent) self.resize (600,300) self.setWindowTitle ('example of creating button and button click event') self.button1 = QPushButton ('keystroke 1' Self) self.button1.clicked.connect (self.clickButton) def clickButton (self): sender = self.sender () print (sender.text () + 'clicked') if _ _ name__ = ='_ main__': app = QApplication (sys.argv) main = MainWindow () main.show () sys.exit (app.exec_ ())

Interpretation of each statement:

Self.button1 = QPushButton ('button 1 button, self): create a button object, the text on the button object appears as button 1, and the second parameter, self, indicates that we have placed the created button object on the QMainWindow object that we have created.

Self.button1.clicked.connect (self.clickButton): execute our custom clickButton function when we click button button 1 that we created. Note that the self.clickButton here cannot be parenthesized, otherwise an error will be reported.

Sender = self.sender (): here self.sender () refers to the object that sends the signal, so we can get the object button 1 that sends the signal.

Sender.text (): gets the name of the object that sends the signal so that we can get the name of button 1.

At this point, the study on "python programming PyQt5 to create buttons and trigger click events" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Buttons objects buttons events methods tutorials programming learning signals names more built help practical next code examples functions parameters parentheses Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL vpn Xiaomi Microsoft Huawei