对于这个PyQt代码,当我点击输出GUI中的相应按钮时,它会显示:
NameError: global name 'n' is not defined
以下是代码:
class MyDialog5(QDialog):
def __init__(self, parent=None):
super(MyDialog5, self).__init__(parent)
self.setGeometry(360,380,360,380)
self.setWindowTitle('Distribution')
self.table = QTableWidget()
self.table.setColumnCount(2)
self.table.setRowCount(10)
self.table.setAlternatingRowColors(True)
self.table.setItem(11,1, QTableWidgetItem('224'))
self.table.setSelectionBehavior(QTableWidget.SelectRows)
self.table.setHorizontalHeaderLabels(["x", "y"])
data1 = ['blue', 'red']
data2 = ['1','1']
for i in range(2):
item1 = QTableWidgetItem(data1[i])
self.table.setItem(i,0,item1)
item1.setFlags(Qt.ItemIsEditable)
item1.setForeground(QColor('black'))
item2 = QTableWidgetItem(data2[i])
self.table.setItem(i,1,item2)
item2.setForeground(QColor('black'))
self.pbutton1 = QPushButton('clicke here')
self.pbutton1.clicked.connect(self.on_pbutton1_clicked)
self.pbutton2 = QPushButton('Set Defaults')
rightLayout = QVBoxLayout()
rightLayout.addWidget(self.pbutton1)
rightLayout.addWidget(self.pbutton2)
rightLayout.addStretch(1)
self.buttonBox = QDialogButtonBox(self)
self.buttonBox.setOrientation(Qt.Horizontal)
self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|
QDialogButtonBox.Ok)
mainLayout = QHBoxLayout()
mainLayout.addWidget(self.table)
mainLayout.addLayout(rightLayout)
self.verticalLayout = QVBoxLayout(self)
self.verticalLayout.addLayout(mainLayout)
self.verticalLayout.addWidget(self.buttonBox)
def on_pbutton1_clicked(self):
global n
n == data2
n = [int(i) for i in n]
if sum(n) != 0:
print "none"
答案 0 :(得分:2)
变化
n == data2
到
n = data2
并注意你的错误消失。 :)
答案 1 :(得分:1)
很好。 n
第一次出现是
n == data2
尚未定义。
答案 2 :(得分:0)
n == data2
行在分配之前尝试访问n
。这条线似乎也没有尝试做一些有用的事情;如果你删除它,你的问题应该消失,没有任何负面影响。
答案 3 :(得分:0)
正在引发NameError,因为您在为n == data2
分配值之前进行了比较n
。
global
关键字仅声明应将以下变量添加到全局范围;你仍然需要为变量赋值以便使用它。