需求:实现按钮互斥选中
效果
未点击状态:
点击BT1:
点击BT2:
文件:untitled.py
代码:
python
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'untitled.ui'
#
# Created by: PyQt5 UI code generator 5.15.9
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(532, 232)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(60, 70, 121, 41))
self.pushButton.setObjectName("pushButton")
self.pushButton_2 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_2.setGeometry(QtCore.QRect(200, 70, 121, 41))
self.pushButton_2.setObjectName("pushButton_2")
self.pushButton_3 = QtWidgets.QPushButton(self.centralwidget)
self.pushButton_3.setGeometry(QtCore.QRect(350, 70, 121, 41))
self.pushButton_3.setObjectName("pushButton_3")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 532, 23))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "BT1"))
self.pushButton_2.setText(_translate("MainWindow", "BT2"))
self.pushButton_3.setText(_translate("MainWindow", "BT3"))
文件:test.py
代码:
python
from untitled import Ui_MainWindow
from PyQt5.QtWidgets import QMainWindow, QApplication
import sys
class MainFun(Ui_MainWindow, QMainWindow):
def __init__(self):
super(MainFun, self).__init__()
self.setupUi(self)
# PyQT5 按钮默认颜色为浅灰
self.button_default_css = "background-color: light gray;"
self.button_selected_css = "background-color: yellow;"
# 用于记录上一个被点击的按钮
self.check_btn = None
self.pushButton.clicked.connect(self.checked)
self.pushButton_2.clicked.connect(self.checked)
self.pushButton_3.clicked.connect(self.checked)
def checked(self):
sender = self.sender()
if sender == self.check_btn:
return
if self.check_btn:
self.check_btn.setStyleSheet(self.button_default_css)
sender.setStyleSheet(self.button_selected_css)
# 记录当前被点击的按钮
self.check_btn = sender
if __name__ == '__main__':
app = QApplication(sys.argv)
ui = MainFun()
ui.show()
sys.exit(app.exec_())
参考博客: