当我的代码包含相同的名称时,我不确定为什么会出现名称错误?这是密码。我认为权重值应该从onBtnPress传递到fcn()。这里有我遗漏的东西吗
错误 NameError: name 'fcn' is not defined
weightValue = ""
class keypad(App):
def onBtnPress(self, btn):
global weightValue
if btn.text == "Clear":
weightValue = weightValue[:-10]
elif btn.text == "Enter":
print("the value has be sent")
#send value to weight calculator
else:
weightValue = weightValue + btn.text
fcn(weightValue)
#send value to label
def fcn(self, weightValue):
print(weightValue)
def build(self):
layout = GridLayout(cols=2)
# , spacing=15, padding=15, row_default_height=40
# Make the background gray:
with layout.canvas.before:
Color(.2,.2,.2,1)
self.rect = Rectangle(size=(800,600), pos=layout.pos)
leftBox = GridLayout(cols=2)
lblweight = Label(text='Weight in pounds: ')
weightValuelbl = Label(text=weightValue)
leftBox.add_widget(lblweight)
leftBox.add_widget(weightValuelbl)
rightBox = GridLayout(cols=3)
_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, "Clear", 0, "Enter"]
for num in _list:
rightBox.add_widget(Button(text=str(num), on_release=self.onBtnPress))
layout.add_widget(leftBox)
layout.add_widget(rightBox)
return layout
if __name__ == '__main__':
keypad().run()
您试图调用常规的函数
fcn
,但没有这样的函数。您确实有一个名为的实例方法,但这不是您所调用的方法。请阅读关于类和方法的教程。要修复此用法,您需要执行以下两项操作之一:正确调用实例方法,例如
或
将函数
fcn
移到类外,它将成为一个“普通”函数请注意,您没有以任何方式在函数中使用
self
;为什么fcn
在类中?正如前面的回答所指出的,由于您所做的只是将其作为对print
的受限(单值)调用,因此它似乎没有什么用处相关问题 更多 >
编程相关推荐