from PyQt5.QtWidgets import QRadioButton, QLabel, QVBoxLayout, QApplication, QHBoxLayout
from PyQt5 import QtWidgets
from PyQt5.QtCore import Qt
class RadioButton(QtWidgets.QWidget):
def __init__(self):
QtWidgets.QWidget.__init__(self)
self.setWindowTitle('单选框演示')
self.setGeometry(200, 200, 300, 100)
self.rb1 = QRadioButton('单选框1', self)
self.rb2 = QRadioButton('单选框2', self)
self.rb3 = QRadioButton('单选框3', self)
self.rb4 = QRadioButton('单选框4', self)
self.rb1.setFocusPolicy(Qt.NoFocus)
self.rb2.setFocusPolicy(Qt.NoFocus)
self.rb3.setFocusPolicy(Qt.NoFocus)
self.rb4.setFocusPolicy(Qt.NoFocus)
self.rb2.toggle() #初始化时单选框1被勾上,其他未被勾选
self.rb1.toggled.connect(self.changeText)
self.rb2.toggled.connect(self.changeText)
self.rb3.toggled.connect(self.changeText)
self.rb4.toggled.connect(self.changeText)
self.label = QLabel()
self.label.setText('单选框2')
self.vbox = QVBoxLayout()
self.vbox.addWidget(self.rb1)
self.vbox.addWidget(self.rb2)
self.vbox.addWidget(self.rb3)
self.vbox.addWidget(self.rb4)
self.vbox1 = QVBoxLayout()
self.vbox1.addWidget(self.label)
self.hbox = QHBoxLayout()
self.hbox.addLayout(self.vbox)
self.hbox.addLayout(self.vbox1)
self.setLayout(self.hbox)
def changeText(self):
if self.rb1.isChecked():
self.label.setText('单选框1')
elif self.rb2.isChecked():
self.label.setText('单选框2')
elif self.rb3.isChecked():
self.label.setText('单选框3')
elif self.rb4.isChecked():
self.label.setText('单选框4')
else:
self.label.setText('没有勾选')
if __name__ == "__main__":
import sys
app = QApplication(sys.argv)
qb = RadioButton()
qb.show()
sys.exit(app.exec_())
效果: