如何使用 Python 本身而不是通过鼠标单击来控制复选框?

How to control the checkbox using the Python itself, and not by a mouse click?

我使用 PyQT 创建了一个复选框,通常使用鼠标点击即可。

我想知道是否有一种方法可以使用程序本身取消选中和选中复选框,而不是单击鼠标。 基本上我想在 20 秒内选中和取消选中该框 10 次并显示它正在发生。

这是我的复选框代码:

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QCheckBox, QWidget
from PyQt5.QtCore import QSize    

class ExampleWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(140, 40))    
        self.setWindowTitle("Checkbox") 

        self.b = QCheckBox("Yes",self)
        
        self.b.move(20,20)
        self.b.resize(320,40)

 
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = ExampleWindow()
    mainWin.show()
    sys.exit( app.exec_() )

checked : bool

This property holds whether the button is checked Only checkable buttons can be checked. By default, the button is unchecked.

QTimer class 提供重复和单次定时器。 更多... https://doc.qt.io/qt-5/qtimer.html

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QCheckBox, QWidget
from PyQt5.QtCore import QSize    

class ExampleWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setMinimumSize(QSize(140, 40))    
        self.setWindowTitle("Checkbox") 

        self.b = QCheckBox("Yes",self)
        
        self.b.move(20,20)
        self.b.resize(320,40)
        
        self.num = 0
        self.timer = QtCore.QTimer()
        self.timer.setInterval(2000)                 # msec
        self.timer.timeout.connect(self.update_now)
        self.timer.start()

    def update_now(self):
        self.b.setChecked(not self.b.isChecked())               # +++
        self.num += 1
        if self.num == 10: self.timer.stop()

 
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = ExampleWindow()
    mainWin.show()
    sys.exit( app.exec_() )