You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Python Kivy中修改按钮的文本颜色

How to Change Button Text Color in Kivy (White Background, Black Text)

I’ve run into this exact snag before—Kivy’s default button styling can feel opaque at first, but there are a few straightforward ways to get the white background + black text look you’re after. Here are the most reliable methods:

Method 1: Set Properties Directly in Python

You can define the button’s appearance right in your Python code by targeting two key properties: color (for text) and background_color. Note that Kivy uses RGBA values (each from 0 to 1) for colors. A critical detail: to make your background color visible, you’ll need to clear Kivy’s default button image by setting background_normal to an empty string.

from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    def build(self):
        btn = Button(
            text="My Styled Button",
            color=(0, 0, 0, 1),  # Black text (RGBA)
            background_color=(1, 1, 1, 1),  # White background (RGBA)
            background_normal=""  # Remove default background image
        )
        return btn

if __name__ == "__main__":
    MyApp().run()

Kv is Kivy’s dedicated styling language, which keeps UI code separate from logic and is far more maintainable for larger projects. Here’s how to implement the same style:

First, create a .kv file named after your app class (e.g., myapp.kv):

<CustomButton>:
    color: 0, 0, 0, 1  # Black text
    background_color: 1, 1, 1, 1  # White background
    background_normal: ""  # Clear default button image

Button:
    text: "Styled with Kv"
    # Uncomment below to use the reusable custom class
    # class: CustomButton

Then your Python code:

from kivy.app import App
from kivy.uix.button import Button

class CustomButton(Button):
    pass  # Reusable button class for consistent styling

class MyApp(App):
    def build(self):
        return Button()  # Or return CustomButton() for the styled class

if __name__ == "__main__":
    MyApp().run()

Method 3: Global Styling with a Style Sheet

If you want every button in your app to use this style, apply a global rule using Kivy’s Builder:

from kivy.app import App
from kivy.uix.button import Button
from kivy.lang import Builder

# Apply style to all Button widgets
Builder.load_string("""
<Button>:
    color: 0, 0, 0, 1
    background_color: 1, 1, 1, 1
    background_normal: ""
""")

class MyApp(App):
    def build(self):
        return Button(text="Globally Styled Button")

if __name__ == "__main__":
    MyApp().run()

Critical Note:

The background_normal property is non-negotiable here. Without setting it to an empty string, Kivy’s default button image will overlay your background color, making it seem like your color changes aren’t working—this is the most common reason people struggle with this!

Content of the question originates from Stack Exchange, asked by Tom

火山引擎 最新活动