使用QRadioButton().toggled.connect連接需要變化的函數,在函數中通過判斷單選框狀態()來self.sender().isChecked()進行變化
QRadioButtonDemo.py
""" 單選按鈕控件(QRadioButton) """ import sys from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * class QRadioButtonDemo(QWidget): def __init__(self): super(QRadioButtonDemo, self).__init__() self.initUI() def initUI(self): self.setWindowTitle("QRadioButton") layout = QHBoxLayout() self.button1 = QRadioButton("單選按鈕1") self.button1.setChecked(True) self.button1.toggled.connect(self.buttonState) layout.addWidget(self.button1) self.button2 = QRadioButton("單選按鈕2") self.button2.toggled.connect(self.buttonState) layout.addWidget(self.button2) self.button3 = QRadioButton("單選按鈕3") self.button3.toggled.connect(self.buttonState) layout.addWidget(self.button3) self.setLayout(layout) def buttonState(self): radioButton = self.sender() if radioButton.isChecked() == True: print('<' + radioButton.text() + '> 被選中') else: print("<" + radioButton.text() + "> 被取消選中狀態") if __name__ == "__main__": app = QApplication(sys.argv) main = QRadioButtonDemo() main.show() sys.exit(app.exec_())