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

求助:按指定书籍操作Kivy中Label组件颜色无法修改

解决Kivy Label文本颜色不生效的问题

嘿,我一眼就发现问题所在啦!你的代码里有个关键错误:你在KV语言里定义了<WeatherApp>规则,但WeatherApp是继承自App的类,并不是Kivy的Widget组件,所以这个规则根本不会被应用到界面上,自然设置的color属性也不会生效。

下面给你两种可行的修正方案:

方案一:直接加载根布局

去掉KV语言里的<WeatherApp>声明,直接定义根BoxLayout,让Builder加载后直接作为界面的根组件:

from kivy.lang import Builder
from kivy.app import App

root_widget = Builder.load_string('''
BoxLayout:
    Label:
        text: 'hey !'
        color: 1, 1, 1, 1  # 白色文本
    Label:
        text: 'mark !'
        color: 0, 1, 0, 1  # 绿色文本,方便测试效果
    Label:
        text: 'what is up ?'
        color: 1, 0, 0, 1  # 红色文本
''')

class WeatherApp(App):
    def build(self):
        return root_widget

if __name__ == '__main__':
    WeatherApp().run()

方案二:定义自定义Widget作为根

如果想保留KV规则的写法,可以创建一个自定义Widget类,然后在KV里针对这个类写布局规则:

from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout

Builder.load_string('''
<RootLayout>:
    Label:
        text: 'hey !'
        color: 1, 1, 1, 1
    Label:
        text: 'mark !'
        color: 0, 1, 0, 1
    Label:
        text: 'what is up ?'
        color: 1, 0, 0, 1
''')

class RootLayout(BoxLayout):
    pass

class WeatherApp(App):
    def build(self):
        return RootLayout()

if __name__ == '__main__':
    WeatherApp().run()

额外小提示

  • Label的color属性是RGBA格式,四个值分别对应红、绿、蓝、透明度,取值范围都是0到1之间。
  • 如果修改后还是看不到颜色变化,可以检查窗口背景色——比如背景是白色的话,白色文本就会“隐身”,我在示例里特意换成了不同颜色方便你测试~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:33:33