【问题标题】:Increasing value of variable via button in kivy通过kivy中的按钮增加变量的值
【发布时间】:2019-12-31 02:02:26
【问题描述】:

我正在尝试增加变量值,但出现此错误:

"UnboundLocalError: 赋值前引用了局部变量 'x'"

有人可以帮帮我吗?

.kv:

<InputValuesScr>:
    GridLayout:
        rows:2
        TextInput:
            input_filter: 'float'
            font_size: 50
            text: 'Please, input value of x1'
            id: xval
            multiline: False
            on_touch_down: self.text = ''
        Button:
            text: 'Submit'
            on_press: root.x_changer()

.py:

global x
x = 1

class TypeOfGeometryScr(Screen):
    pass

class SelectDemensionsScr(Screen):

    def submit_dn(self):
        global dn
        dn = self.ids.demensions.text

class InputValuesScr(Screen):

    def x_changer(self):
        x = x
        x += 1
        self.ids.xval.text = 'Please, input value of x' + str(x)

【问题讨论】:

  • 欢迎来到 Stack Overflow!您的错误消息是关于 local 变量 x,并且在您的代码中,您定义了一个全局 x 一个本地 x。如果在函数中使用变量,Python 要求您指定一个变量是为了引用全局变量。这就是你的意思吗?

标签: python kivy kivy-language


【解决方案1】:

发生这种情况是因为 global x 在全局范围内,而不是在 x_changer() 函数 lac 范围内。为了解决这个问题,您需要将global x 移动到函数的本地范围内

def x_changer(self):
        global x
        x = x
        x += 1
        self.ids.xval.text = 'Please, input value of x' + str(x)

【讨论】:

  • 非常感谢
  • 如果这是您正在搜索的答案,请考虑接受答案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-09-20
  • 1970-01-01
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
相关资源
最近更新 更多