Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在PYQT initUI函数中增加变量名?_Python_Python 3.x_Pyqt_Pyqt5 - Fatal编程技术网

Python 如何在PYQT initUI函数中增加变量名?

Python 如何在PYQT initUI函数中增加变量名?,python,python-3.x,pyqt,pyqt5,Python,Python 3.x,Pyqt,Pyqt5,下面是我的代码: class Example(QWidget): def __init__(self, fname): self.fname=fname super().__init__() self.initUI() def initUI(self): #self.cb1 = QCheckBox('all',self) self.cb2 = QCh

下面是我的代码:

class Example(QWidget):

    def __init__(self, fname):
        self.fname=fname
        super().__init__()
        self.initUI()


    def initUI(self):
    
        #self.cb1 = QCheckBox('all',self)

                
        self.cb2 = QCheckBox('a',self)
        self.cb3 = QCheckBox('b',self)
        self.cb4 = QCheckBox('c',self)
        #for x in range(1, 13): 
         #   locals()['self.cb{0}'.format(x)] = QCheckBox('a',self)
        
            
        bt = QPushButton('submit',self) 

        self.resize(300,200)
        self.setWindowTitle('sheets selction')

我试图通过循环的输入量来增加
self.cb
,所以我想增加循环中的
self.cb
,比如
self.cb1
self.cb2
self.cb3
,我尝试使用
locals()
,它在PYQT中工作,但当我尝试在
initUI
中使用它时,它不起作用,有人知道如何增加它吗?

您可以使用
setattr
直接创建具有所需名称的属性。
您注释掉的代码应为:

for x in range(1, 13): 
    setattr(self, f"cb{x}", QCheckBox('a', parent=self))
根据你发布的代码,我相信这更接近你想要的:

for x, string in enumerate("all a b c d e f g h i j k".split(), start=1):
    setattr(self, f"cb{x}", QCheckBox(string, parent=self))
相当于

    self.cb1 = QCheckBox('all', self)     
    self.cb2 = QCheckBox('a', self)
    self.cb3 = QCheckBox('b', self)
    self.cb4 = QCheckBox('c', self)
    ...
    self.cb12 = QCheckBox('k', self)

我要分享我的想法。在列表中存储复选框怎么样?甚至字典:

self.checkboxes_dictionary = {}
self.checkboxes_list = []
names = ["a", "b", "c", "d"]
for name in names:
    self.checkboxes_dictionary[name] = QCheckBox(name, parent=self)
    self.checkboxes_list.append(QCheckBox(name, parent=self))

当您发现自己想要这样做时,应该使用一个列表。
self.cb=[QCheckBox(chr(ord('a')+i),self)for i in range(12)]
这很有帮助,谢谢您是Python标准库的一部分,不应该用作变量。