-1

当我的代码包含相同的名称时,我不确定为什么会收到 NameError?这是代码。我相信 weightValue 应该从 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()
4

1 回答 1

0

您试图调用通用函数 fcn,但没有这样的函数。您确实有一个该名称的实例方法,但这不是您所说的。请查看您关于类和方法的教程。您需要执行以下两项操作之一来修复此用法:

正确调用您的实例方法,例如

self.fcn(weightValue)

- 或者 -

将函数fcn移到类之外,它将成为“正常”函数。

请注意,您没有self以任何方式在函数中使用过;为什么fcn在课堂上?正如前面的答案所指出的,由于您所做的只是将其设为对 的受限(单值)调用print,因此它似乎没有任何用处。

于 2020-04-28T16:55:56.343 回答