Python/kivy类型错误:'kivy.properties.ObjectProperty'对象不是iterab

2024-10-03 17:18:45 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我一直在为我的项目做一个掷骰子,我称之为:地牢主的助手,因为他帮助了我的DM,但现在让我们谈谈我的问题。在

当我按下按钮RollDice,它需要两个文本输入(骰子的类型和数量)和掷骰子,然后现在在控制台上打印骰子的数量和类型以及结果。然而,这反而使程序崩溃。在

这是相关的python代码(如果需要,可以显示更多):

class DiceRoller(Screen):

    def rolldice(self):
        self.diceNumber = ObjectProperty()
        self.diceType = ObjectProperty()


        print(F"{self.diceNumber}D{self.diceType}")


        for x in self.diceNumber:
            x = x + 1

            ActualDie = random.randint(1, self.diceType)
            Total = Total + ActualDie

            print(Total)

下面是调用上述函数的按钮:

^{pr2}$

正如我说的,它应该打印,例如6D6,然后打印骰子的总数。但是,发生的情况如下(错误代码):

enter image description here

该值由同一屏幕上的两个文本输入框设置:kv文件中的link。在

Screen - ObjectProperty links to TextInput


Tags: 项目文本self类型数量助手骰子按钮
2条回答

属性使用错误,必须在类级别声明它们:

class DiceRoller(Screen):
    diceNumber = ObjectProperty()
    diceType = ObjectProperty()

    def rolldice(self):
        print(F"{self.diceNumber}D{self.diceType}")
        # etc.

您还需要在访问它们之前将它们设置为实际值,但我假设您没有显示的代码已经涵盖了这一点。在

问题-ObjectProperty@method level

参考您提供的原始代码,即在方法级别声明的ObjectProperty。在

根本原因

原因是当您将TextInput小部件链接到kv文件中的属性时,Kivy将在相关的类/小部件中查找这些属性。如果类/小部件没有具有给定名称的属性,则会自动创建一个ObjectProperty并将其添加到类/小部件中。在

当应用程序重新初始化方法中ObjectProperty类型的两个自动创建的类属性rolldice(),并为其分配默认值None时,链接被中断。在

解决方案

  • 引用TextInput对象的text属性,并将字符串转换为整数,int(self.diceNumber.text)和{}
  • range()函数添加到for循环中
  • 在类级别声明ObjectProperty(这是可选的)

代码段-示例

class DiceRoller(Screen):
    diceNumber = ObjectProperty(None)
    diceType = ObjectProperty(None)

    def rolldice(self):
        Total = 0    # initialize Total
        print(F"{self.diceNumber.text}, D{self.diceType.text}")

        for x in range(int(self.diceNumber.text)):

            ActualDie = random.randint(1, int(self.diceType.text))
            Total += ActualDie

        print(Total)

示例

下面的例子说明Kivy自动创建了diceNumber和{}类型的两个类属性。在

在主.py在

^{pr2}$

相关问题 更多 >