PyQt5按鈕單擊事件,退出程序

1.注意項(xiàng):

當(dāng)使用QPushButton.clicked.connect(lambda:self.信號(hào)槽方法)。connect方法傳參數(shù)時(shí),需要加上“l(fā)ambda:”

2.步驟:

  • 添加一個(gè)按鈕 self.button1 = QPushButton('按鈕上的文本')。
  • 創(chuàng)建水平布局對(duì)象QHBoxLayout,并使用setWidget方法,將button1添加進(jìn)去。
    layout = QHBoxLayout()
    layout.addWidget(self.button1)
  • 主框架Widget,所有組件的根。將所有組件添加到主框架中。
    mainFrame = QWidget()
    mainFrame.setLayout(layout)
  • 將主框架放在主窗口
    self.setCentralWidget(mainFrame)
  • 自定義槽:用來處理button的點(diǎn)擊事件。onClick_Button()
    sender = self.sender() \獲取哪一個(gè)組件是發(fā)送者
  • 將按鈕的信號(hào)與槽關(guān)聯(lián)在一起
    self.button1.clicked.connect(lambda: self.onClick_Button())
import sys
from PyQt5.QtWidgets import QHBoxLayout, QMainWindow, QApplication, QPushButton, QWidget


class QuitApplication(QMainWindow):
    def __init__(self):
        super(QuitApplication, self).__init__()
        self.resize(300, 400)
        self.setWindowTitle('退出應(yīng)用程序')

        # 添加button
        self.button1 = QPushButton('退出應(yīng)用程序')
        self.button1.clicked.connect(lambda: self.onClick_Button())

        # 創(chuàng)建水平布局對(duì)象
        layout = QHBoxLayout()
        # 將組件添加到水平布局上
        layout.addWidget(self.button1)

        # 將所有部件都放在mainFrame上
        mainFrame = QWidget()
        # 將layout的內(nèi)容放在mainFrame上
        mainFrame.setLayout(layout)

        # 將mainFrame放在主窗口上
        self.setCentralWidget(mainFrame)

    # 按鈕單擊事件(自定義的槽)
    def onClick_Button(self):
        # 通過sender(發(fā)件人)方法來獲取哪一個(gè)組件是發(fā)送者
        sender = self.sender()
        print(sender.text() + ' 按鈕被按下')

        # 得到一個(gè)實(shí)例
        app = QApplication.instance()
        # 退出應(yīng)用程序
        app.quit()



if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = QuitApplication()
    main.show()
    sys.exit(app.exec_())
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容