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

如何在Python脚本中实例化Kivy kv文件定义的自定义Widget?

在Python中实例化Kivy kv文件定义的自定义Widget

解决方案:使用Kivy Factory模块

kv文件中定义的<News@Label>属于动态创建的类,不会自动出现在Python的命名空间中,你需要通过Factory模块来获取并实例化这个自定义Widget:

  1. 导入Factory模块
    在Python脚本开头添加:
from kivy.factory import Factory
  1. 修改实例化代码
    把你原来创建Label的代码替换为Factory.News,不需要cls参数:
class BiteApp(App):
    def build(self):
        return MyGrid()
    
    def on_start(self):
        app = App.get_running_app()
        news_list = newsScrape.getNewsGlobal()
        for story in news_list:
            app.root.ids.newsGrid.add_widget(Factory.News(text=story))

(优化了循环写法,直接遍历列表元素,更简洁)

另一种思路:Python中定义类+kv绑定样式

如果你希望能像普通Widget一样直接在Python中引用类名,也可以采用「Python定义类+kv绑定样式」的方式:

Python代码:

from kivy.uix.label import Label

class News(Label):
    pass

kv文件:

<News>:
    font_size: 25
    color: 0, 0, 0, 1
    font_family: 'Serif'

这样之后,你就能直接在Python中用News(text="xxx")来实例化自定义Widget了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:50:28