获取错误AttributeError:“FlashDisplayPage”对象没有“label\u name”属性

2024-04-26 03:01:56 发布

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

我正在我的应用程序的FlashDisplayPage中使用carousel。我想在旋转木马里用标签。我搜索了相关网站并做了以下代码。我是新来基维,所以我不知道这是不是正确的方式。如果不是的话,我怎么做才对呢

这里也发生了一个错误,尽管我在FlashDisplayPage中定义了label\u name,但是我得到了这个错误AttributeError:'FlashDisplayPage'对象没有属性'label\u 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()

Tags: 代码textnameselfjsonondef错误
2条回答

label_name是onenter函数中的局部变量,局部变量只能在创建它们的函数或作用域中访问。如果您想访问,一个可能的解决方案是将其作为小部件的属性:

from kivy.properties import StringProperty

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

尝试使用self.label_name创建实例变量,而不是on_enter()中仅具有局部作用域的局部变量

相关问题 更多 >