首页 > 解决方案 > 如何根据 PyQT5 单选按钮选择运行正确的功能

问题描述

我有两个功能,两个单选按钮和一个按钮。

def A():
    pass
def B():
    pass

如果在按下按钮时选择了单选按钮 A,我如何运行功能 A,如果选择单选按钮 B,我如何运行功能 B?我试过类似的东西

if dlg.A_radioButton.clicked:
    dlg.calculate_pushButton.clicked.connect(A)
elif dlg.B_radioButton.clicked:
    dlg.calculate_pushButton.clicked.connect(B)

标签: python-3.xpyqt5

解决方案


试试看:

import sys
from PyQt5.QtWidgets import (QLabel, QRadioButton, QPushButton, QVBoxLayout, QApplication, QWidget)


class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.init_ui()

    def init_ui(self):
        self.lbl = QLabel('Which do you like ?')
        self.rb1 = QRadioButton('PyQt4')
        self.rb2 = QRadioButton('PyQt5')
        self.rb2.setChecked(True)
        self.btn = QPushButton('Select')

        layout = QVBoxLayout()
        layout.addWidget(self.lbl)
        layout.addWidget(self.rb1)
        layout.addWidget(self.rb2)
        layout.addWidget(self.btn)

        self.setLayout(layout)
        self.setWindowTitle('PyQt5 QRadioButton')

        self.btn.clicked.connect(lambda: self.btn_clk(self.rb1.isChecked(), self.lbl))

    def btn_clk(self, chk, lbl):
        if chk:
            lbl.setText('It1s time to switch to PyQt5.')
            self.A('It1s time to switch to PyQt5.')
        else:
            lbl.setText('It`s a great choice!')
            self.B('It`s a great choice!')

    def A(self, text):
        print(text)

    def B(self, text):
        print(text)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(app.exec_())

在此处输入图像描述


推荐阅读