python - 收到错误 AttributeError : 'FlashDisplayPage' object has no attribute 'label_name'

标签 python kivy

我在我的应用程序的 FlashDisplayPage 中使用轮播。我想在旋转木马内使用标签。我搜索了相关网站并编写了以下代码。我是 kivy 的新手,所以我不知道这是否是正确的方法。如果不是,我怎样才能使它正确?

这里也发生错误,即使我在 FlashDisplayPage 中定义了 label_name,我也收到此错误 - AttributeError: 'FlashDisplayPage' 对象没有属性 'label_name'。为什么会出现这个错误?我怎样才能删除它?

这里是发生错误的代码部分-

class FlashDisplayPage(Screen):
    def on_enter(self):
        Num=self.index
        card=['flash_card1.json','flash_card2.json','flash_card3.json','flash_card4.json','flash_card5.json','flash_card6.json','flash_card7.json','flash_card8.json','flash_card9.json','flash_card10.json']
        label_name='Flash Card '+ Num             #here I have defined label_name
        with open(card[Num+1]) as frfile:
            flash_data=json.load(frfile)

        for i in flash_data:

            self.ids.CarDisplay.add_widget(Label(text=i['word']+' : '+i['meaning'])) 
            # here I am adding label to carousel

    def next_one(self):
        self.ids.CarDisplay.direction='right'   # next label in carousel


    def previous_one(self):
        self.ids.CarDisplay.direction='left'    # previous label in carousel

这里是与此相关的 kv 代码部分-

<FlashDisplayPage>:
    BoxLayout:
        orientation: 'horizontal'
        spacing:15
        padding: 20
        Label:
            id: l
            text: root.label_name
            sixe_hint_y: None
            height: 100

        Carousel:
            id: CarDisplay
            loop: True
            Button:
                text:'next'
                size_hint: None,.20
                width: 30
                on_press:root.next_one()
            Button:
                text:'next'
                size_hint: None,.20
                width: 130
                on_press:root.previous_one()

最佳答案

label_name 是 on_enter 函数中的局部变量,局部变量只能在创建它们的函数或范围内访问。如果您希望可访问,一个可能的解决方案是使其成为小部件的属性:

from kivy.properties import StringProperty

class FlashDisplayPage(Screen):
    label_name = StringProperty("")
    def on_enter(self):
        [...]
        self.label_name='Flash Card {}'.format(Num)
        [...]

关于python - 收到错误 AttributeError : 'FlashDisplayPage' object has no attribute 'label_name' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49080919/

相关文章:

python - 未安装 SDK 管理器

scrollview - 设置 kivy scrollview effects_cls 属性的正确方法是什么?

python - 自动关闭 kivy 中的弹出窗口

python - 如何使用 Kivy 制作工具提示?

Python 在保持顺序的同时从列表中删除一些重复项?

python - 在 python beautifulsoup 中查找与其他字符串共享同一类的字符串

python - 全局列表不断变化,尽管复制

python - Kivy - 解除绑定(bind)到按钮的所有方法

python - 从 C API 访问 Python 回溯

python - Django:如何更改内联表单集中的字段小部件