Kivy: 将背景颜色改为白色

30

我希望有一个黑色按钮和标签的应用,文本为白色,并且希望在这些小部件之间有白色空间。我认为,为了实现这一点,需要将默认背景颜色从黑色更改为白色。最佳方法是什么?谢谢!

3个回答

78

一种简单的方法是在您的根部小部件后面简单地绘制一个大白色矩形。例如,在kivy语言中,您可以这样做:

一种简单的方法是在您的根部小部件后面简单地绘制一个大白色矩形。例如,在kivy语言中,您可以这样做:

<MyRootWidget>
    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size
    ...
</MyRootWidget>
<YourRootWidget>:
    canvas.before:
        Color:
            rgba: 1, 1, 1, 1
        Rectangle:
            pos: self.pos
            size: self.size

我认为您实际上可以直接设置Kivy清除窗口背景的颜色,这是公开的Window.clearcolor。您可以使用以下命令:

Window.clearcolor = (R, G, B, A)
from kivy.core.window import Window
Window.clearcolor = (1, 1, 1, 1)

如果在窗口创建后运行,它不会影响任何东西,因此你可能需要将其放在应用程序中的任何其他内容之前。


2
谢谢!有趣的是,似乎“Window.clearcolor”解决方案可以在任何时候使用,而不仅仅是在窗口创建之前。 - James_L
1
好的,我猜ClearColor指令在图形树的顶部。只要它能工作! - inclement
我喜欢这个!我花了很长时间来调整乒乓球的背景颜色 :D - Pitto
我该如何将它绘制在标签部件的后面? - Charles Merriam
此代码应在标签画布上的其余内容之前添加矩形。 - inclement
这对于SettingsWithTabbedPane类不起作用。我在kivy安装目录中的style.kv文件中更改了背景颜色。 - Halil İbrahim Oymacı

1
我已创建了一个模块以实现此目的。请查看:Github上的详细信息
#Change background color of a kivy layout
#Place the CustomGraphics.py file to a folder
#code starts here

import sys
sys.path.append([path to CustomGraphics.py])
from CustomModules import CustomGraphics
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.label import Label

class TestApp(App):
    def build(self):
        layout = BoxLayout(orientation='vertical', size=(Window.width, Window.height))
        label = Label(text="Remember my name: It's Smruti Ranjan Gochhayat")
        layout.add_widget(label)
        CustomGraphics.SetBG(layout, bg_color=[1,0,0,1])
        return layout
if __name__ == '__main__':
    TestApp().run()
    
#code ends here

我希望这对一些人有所帮助


1
你应该直接在这里发布函数的代码。同时,CustomGraphics不需要继承自App。 - Etienne D

0
每个布局都有一个画布,可以用作canvas.before或canvas.after,然后您就可以获得所需的输出。 如果您有某种布局,比如BoxLayout,那么您可以使用canvas.before和Color指令来实现这样的效果。
这里我展示了一个更复杂的例子,其中包含一张图片,我正在尝试在一个食品应用中使用。
<MainUI>:
BoxLayout:
    orientation:"vertical"
    padding:10
    spacing:10
    canvas.before:
        Color:
            rgba:1,1,1,0.4
        Rectangle:
            pos:self.pos
            size:self.size
            source:"images/bg1.png"

这适用于任何东西,并且看起来像这样。

enter image description here

现在,如果你只是将透明度设置为100%或1,在颜色 > rgba 指令中,并且简单地移除图像指令。
<MainUI>:
BoxLayout:
    orientation:"vertical"
    padding:10
    spacing:10
    canvas.before:
        Color:
            rgba:1,1,1,1
        Rectangle:
            pos:self.pos
            size:self.size

并且它将整个背景变为白色。

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接