如何在 Kivy 中更改背景颜色

2022-01-15 00:00:00 python kivy

问题描述

我需要一些帮助,我正在尝试使用 kivy 和 python 3 编写程序,但是我对两者都比较陌生.我在我的程序中需要设置两种不同的背景颜色,用户可以在它们之间切换(一种夜间模式,一种在白天使用)

I need a bit of a hand with a program I'm trying to code using kivy and python 3, however I'm relatively new to both. What I need in my program is to setup two different background colours, that the user can switch between (a night mode, and one to use in daylight)

#globalvariable
backgroundcolour = [50, 50, 50]

class MainScreen(Screen):

    rgb = StringProperty()
    rgb = backgroundcolour

    def changebackground(self):
        self.canvas.clear()
        backgroundcolour = [55, 5, 99]
        print("DONE")

基维文件:

<MainScreen>:
    name: 'main'
    canvas:
        Color: 
            rgb: root.rgb

但是,在我运行 changebackground 子例程之后,我得到的只是我的 kivy 窗口用一个空白的黑屏替换了自己.我想我做错了什么是我没有刷新窗口或其他什么,但我不知道该怎么做.]

However all I get after I run the changebackground subroutine, my kivy window just replaces itself with a blank black screen. I presume what I'm doing wrong is I'm not refreshing the window, or something, but I've got no idea how to go about doing that.]

非常感谢


解决方案

这是一个纯python代码,介绍如何在布局上放背景,没有Kivy设计语言

This is a pure python code on how to put background on layout, no Kivy design language

App 类的代码不包含

供将来参考:

from kivy.uix.gridlayout import GridLayout
from kivy.graphics.vertex_instructions import Rectangle
from kivy.graphics.context_instructions import Color

from kivy.uix import button

class MyLayout(GridLayout):
    def __init__(self, **kwargs):
        super(MyLayout, self).__init__(**kwargs)
        self.cols = 1

        self.bind(
            size=self._update_rect,
            pos=self._update_rect
        )

        with self.canvas.before:
            Color(.20, .06, .31, 1)
            self.rect = Rectangle(
                size=self.size,
                pos=self.pos
            )

    def _update_rect(self, instance, value):
        self.rect.pos = instance.pos
        self.rect.size = instance.size

注意:使用颜色:我的 rgb 值为 (46, 14, 71),然后将其除以 255 (.20, .06, .31, 1).最后一个值是alpha,1是100%

希望对大家有所帮助.只需投票以帮助其他也在寻找答案的人.

Hope it can help you guys. Just up vote to help others who's also looking the answer.

解决您的问题

添加此代码初始化:

self.daylightBtn = button.Button(text="Day Light")
self.daylightBtn.bind(on_press=self.daylight_bg)
            
self.nightlightBtn = button.Button(text="Night Light")
self.nightlightBtn.bind(on_press=self.nighlight_bg)
            
self.add_widget(self.daylightBtn)
self.add_widget(self.nightlightBtn)

按钮事件:

   def daylight_bg(self, instance):
        with self.canvas.before:
            Color(1, 1, 1, 1)
            self.rect = Rectangle(
                size=self.size,
                pos=self.pos
            )


    def nighlight_bg(self, instance):
        with self.canvas.before:
            Color(0, 0, 0, 1)
            self.rect = Rectangle(
                size=self.size,
                pos=self.pos
            )

相关文章