You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy开发时钟应用报错:AttributeError: 'super' object无__getattr__属性

解决Kivy中AttributeError: 'super' object has no attribute '__getattr__'的问题

嘿,我看到你遇到的这个头疼问题了,其实根源是你的kv文件结构出了问题,导致代码找不到你定义的time这个id控件,进而触发了这个看似奇怪的错误。让我一步步帮你解决:

错误原因分析

你在update方法里尝试访问self.root.ids.time.text,但Kivy提示找不到time这个键,这说明你的根组件(也就是BoxLayout)的ids字典里根本没有这个控件。大概率是你的kv文件存在缩进错误,使得那个带有id: time的Label没有被正确嵌套在BoxLayout里面,反而变成了和BoxLayout同级的顶级组件。这时Kivy会把最后一个顶级组件作为App的root,也就是那个Label,而它本身没有子组件,所以ids是空的,自然找不到time。

另外,你用Clock.schedule_interval(self.update, 0)也不太合适——这会让update方法每帧都执行一次,对于时钟来说完全没必要,每秒更新一次就足够了,还能节省性能。

修复方案

1. 修复kv文件的缩进

确保你的clock.kv文件里的Label正确嵌套在BoxLayout中,注意用空格缩进(不要用Tab),正确的代码应该是这样:

<Label>:
    font_name: 'Roboto'
    font_size: 60
    markup: True

BoxLayout:
    orientation: 'vertical'
    Label:
        id: time
        text: '[b]00[/b]:00:00'

2. 调整时钟更新间隔

修改main.py里的on_start方法,把调度间隔改成1(每秒更新一次):

from kivy.app import App
from kivy.clock import Clock
from kivy.core.text import LabelBase
from kivy.core.window import Window
from kivy.utils import get_color_from_hex
from time import strftime


class ClockApp(App):
    def on_start(self):
        # 每秒更新一次时钟,替代原来的每帧更新
        Clock.schedule_interval(self.update, 1)

    def update(self, nap):
        self.root.ids.time.text = strftime('[b]%H[/b]:%M:%S')


if __name__ == '__main__':
    Window.clearcolor = get_color_from_hex('#101216')
    # 务必确保这两个字体文件和代码在同一个目录下
    LabelBase.register(name='Roboto',
                       fn_regular='Roboto-Thin.ttf',
                       fn_bold='Roboto-Medium.ttf')
    ClockApp().run()

额外注意事项

  • 确认Roboto-Thin.ttf和Roboto-Medium.ttf这两个字体文件和你的main.py、clock.kv在同一个文件夹里,否则Kivy会找不到字体,转而使用默认字体。
  • 如果还是遇到问题,可以尝试在App类里显式定义build方法来创建根组件,这样能更直观地控制组件结构:
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label

# ... 其他导入保持不变 ...

class ClockApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')
        time_label = Label(id='time', text='[b]00[/b]:00:00', 
                          font_name='Roboto', font_size=60, markup=True)
        layout.add_widget(time_label)
        return layout

    def on_start(self):
        Clock.schedule_interval(self.update, 1)

    def update(self, nap):
        self.root.ids.time.text = strftime('[b]%H[/b]:%M:%S')

这样修改后,你的时钟应用应该就能正常运行了!

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:13:01