首页 > 解决方案 > 如何获取整数作为用户输入,然后在 Kivy 中用作参数?

问题描述

我是 kivy 的新手,我正在制定锻炼清单。我收集用户想要的组数,在下一个窗口中,我希望用户输入每组的重复次数。为了获得用户输入,我使用了这个

Python代码:

    ActiveExerciseSet = None
    class AddWorkoutWidget(Screen):
        exercise_set = ObjectProperty("0")

        def AddExercise(self):
        ActiveExerciseSet = self.exercise_set.text

基维代码:

<AddWorkoutWidget>
    exercise_set : exercise_set
            Label:
                text: "Number of sets "

            TextInput:
                id: exercise_set
                input_filter: 'int'
                multiline: False

            Button:
                text: 'Number of reps'
                on_press:root.AddExercise()

现在我想使用集合的数量作为循环参数

class AddSetWidget(GridLayout,Screen):
    def __init__(self, **kwargs):
        super(AddSetWidget, self).__init__(**kwargs)  # call grid layout parameters
        self.cols = int(ActiveExerciseSet)
        for I in self.col:
            pass

但我不断收到TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

有没有办法把它变成一个整数?

谢谢

标签: pythonuser-interfacebuttonkivy

解决方案


我认为有一个逻辑错误。事情是这样的

ActiveExerciseSet = None # this is a global variable
class AddWorkoutWidget(Screen):
    exercise_set = ObjectProperty("0")

    def AddExercise(self):
        ActiveExerciseSet = self.exercise_set.text #this creates a local variable within this function

所以当你触发这个函数时,全局变量仍然None是你认为你给它赋值的地方

class AddSetWidget(GridLayout,Screen):
    def __init__(self, **kwargs):
        super(AddSetWidget, self).__init__(**kwargs)  # call grid layout parameters
        self.cols = int(ActiveExerciseSet)
        #this is looking for a local variable
        #and not the global variable
        for I in self.col:
            pass

因此,您会得到错误NoneType- 这是正确的,因为您的全局变量被分配了一个值None

解决方案 为了使用/分配值 a global variable,您需要使用关键字global

def AddExercise(self):
    global ActiveExerciseSet#reference to global variable
    ActiveExerciseSet = self.exercise_set.text


class AddSetWidget(GridLayout,Screen):
    def __init__(self, **kwargs):
        super(AddSetWidget, self).__init__(**kwargs)  # call grid layout parameters
        global ActiveExerciseSet #reference to global variable
        self.cols = int(ActiveExerciseSet)
        for I in self.col:
            pass

推荐阅读