📜  PyQt5 – 切换按钮

📅  最后修改于: 2022-05-13 01:55:12.563000             🧑  作者: Mango

PyQt5 – 切换按钮

在 PyQt5 中,切换按钮基本上是处于特殊状态的按钮。按钮是一个按钮,当我们按下它时,它会执行一些任务并恢复正常状态。它类似于键盘键,当我们按下它时,它会做一些事情,当我们释放它时,它会恢复到原来的形式。

ToggleButton是一种按钮,但它有两种状态,即当我们按下它时,它不会恢复到原始状态。切换按钮类似于电源开关,当我们按下它时,它会保持打开状态,当我们关闭它时,它会保持在关闭位置。

下面是实现。

# importing the required libraries
  
from PyQt5.QtCore import * 
from PyQt5.QtGui import * 
from PyQt5.QtWidgets import * 
import sys
  
  
class Window(QMainWindow):
    def __init__(self):
        super().__init__()
  
        # set the title
        self.setWindowTitle("Python")
  
        # setting geometry
        self.setGeometry(100, 100, 600, 400)
  
        # creating a push button
        self.button = QPushButton("Toggle", self)
  
        # setting geometry of button
        self.button.setGeometry(200, 150, 100, 40)
  
        # setting checkable to true
        self.button.setCheckable(True)
  
        # setting calling method by button
        self.button.clicked.connect(self.changeColor)
  
        # setting default color of button to light-grey
        self.button.setStyleSheet("background-color : lightgrey")
  
        # show all the widgets
        self.update()
        self.show()
  
    # method called by button
    def changeColor(self):
  
        # if button is checked
        if self.button.isChecked():
  
            # setting background color to light-blue
            self.button.setStyleSheet("background-color : lightblue")
  
        # if it is unchecked
        else:
  
            # set background color back to light-grey
            self.button.setStyleSheet("background-color : lightgrey")
  
  
  
# create pyqt5 app
App = QApplication(sys.argv)
  
# create the instance of our Window
window = Window()
  
# start the app
sys.exit(App.exec())

输出 :