首页 > 解决方案 > kivy函数在调用时不访问自身

问题描述

我正在构建一个应用程序来从网页中提取数据,解析该信息,然后使用该信息更新一些标签。该功能由时钟时间表触发。问题是,当我尝试从解析器中获取连接的字符串并更新标签时,我得到“AttributeError:'float' object has no attribute 'flabel0'。没有删除整个 .py 和 . kv 文件,以下是相关位:

class blBox(BoxLayout):
    flabel0 = ObjectProperty(None)
    flabel1 = ObjectProperty(None)  ## etc
    
    def flight_up(self):
        (routine here that scrapes data first, puts it into a text file, which works)

        with open("flt.txt", "r") as fh:
        (parse info and concatenate into string named "tstr", which works)
            if golabel == 1:  ##not all lines in the text file are valid
                if lblcount == 0:  ##pick which label to update
                    self.flabel0.text = tstr  <<-------------------------------- throws the error here

    Clock.schedule_interval(flight_up, 30)

.kv code
<BackgroundColor@Widget>
    background_color: 1, 1, 1, 1
    canvas.before:
        Color:
            rgba: root.background_color
        Rectangle:
            size: self.size
            pos: self.pos
    font_name: 'c:\Windows\Fonts\erasdemi.ttf'

<FLLabel@Label+BackgroundColor>
    color: 0,0,0,1
    background_normal: 'white.png'   ## a little white square
    background_color: .8, .8, 1, 1
    font_name: 'c:\Windows\Fonts\ltypeb.ttf'
    font_size: '22sp'
    halign: 'left'
    valign: 'center'
    texture_size: self.size
    text_size: self.size

<blBox>:
    orientation: 'horizontal'
    flabel0: flt0
    flabel1: flt1 #etc
    BoxLayout:  ## buttons and labels for left side
    BoxLayout:  ## buttons and labels for right side
        id: rightside
        orientation: 'vertical'

        FLlabel:
            id: flt0
            text: 'Arrival'
            background_color: .9, .9, 1, 1

        FLlabel:
            id: flt1
            text: 'Arrival'
            background_color: .8, .8, .9, 1

错误似乎说'self'是一个浮动对象?如果有任何不清楚的地方,请告诉我。谢谢!

标签: pythonkivy

解决方案


既然你已经ids分配了,你可以在你的flight_up()方法中使用它们。此外,该flight_up()方法必须接受dt参数(即时间增量)或一般*args. 所以你flight_up()可以看起来像:

def flight_up(self, *args):
    # (routine here that scrapes data first, puts it into a text file, which works)

    with open("flt.txt", "r") as fh:
        # (parse info and concatenate into string named "tstr", which works)
        if golabel == 1:  ##not all lines in the text file are valid
            if lblcount == 0:  ##pick which label to update
                self.ids.flt0.text = tstr

此外,设置类Clock.schedule_once()方法的外部会blBox导致flight_up作为类方法调用(无self参数)。

__init__()您可以通过添加执行调度的方法来纠正此问题:

class blBox(BoxLayout):
    flabel0 = ObjectProperty(None)
    flabel1 = ObjectProperty(None)  ## etc
    
    def __init__(self, **kwargs):
        Clock.schedule_once(self.flight_up, 30)
        super(blBox, self).__init__(**kwargs)

当然,删除另一个对Clock.


推荐阅读