预览效果
源码
# -*- coding: utf-8 -*-
'''
【简介】
PyQt5中QRadio例子
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class Radiodemo(QWidget):
def __init__(self, parent=None):
super(Radiodemo, self).__init__(parent)
layout = QHBoxLayout() #实例化一个布局
self.btn1 = QRadioButton("Button1") #实例化一个选择的按钮
self.btn1.setChecked(True) #设置按钮点点击状态
self.btn1.toggled.connect(lambda:self.btnstate(self.btn1)) #绑定点击事件
layout.addWidget(self.btn1) #布局添加组件
self.btn2 = QRadioButton("Button2") #实例化第二个按钮
self.btn2.toggled.connect(lambda:self.btnstate(self.btn2)) #绑定按钮事件
layout.addWidget(self.btn2) #布局添加第二个按钮
self.setLayout(layout) #界面添加 layout
self.setWindowTitle("RadioButton demo")
def btnstate(self,btn): #自定义点击事件函数
if btn.text()=="Button1":
if btn.isChecked() == True:
print( btn.text() + " is selected" )
else:
print( btn.text() + " is deselected" )
if btn.text()=="Button2":
if btn.isChecked()== True :
print( btn.text() + " is selected" )
else:
print( btn.text() + " is deselected" )
if __name__ == '__main__':
app = QApplication(sys.argv)
radioDemo = Radiodemo()
radioDemo.show()
sys.exit(app.exec_())