【问题标题】:Change color of canvas with Kivy while running运行时使用 Kivy 更改画布颜色
【发布时间】:2017-02-01 00:19:11
【问题描述】:

我想在跑步时更改画布的颜色。

画布的颜色应该是:

  • 红色如果len(inputtext)%3 == 0
  • 绿色如果len(inputtext)%3 == 1
  • 蓝色如果len(inputtext)%3 == 2

下面代码中的color()方法我不知道怎么写:

kv ="""
RootWidget:
    orientation: 'vertical'

    TextInput:
        id: my_id
        text: 'text'
        on_text: root.color()

    Label:
        id: my_Label
        text: ' '
        canvas.before:
            Color:
                rgb: (1., 1., 0.)
            Rectangle:
                size: self.size
                pos: self.pos
"""

import kivy
kivy.require('1.8.0')

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

class RootWidget(BoxLayout):

    def __init__(self):
        super().__init__()

    def color(self):
        pass  # <-- here

class TestApp(App):
    def build(self):
        return Builder.load_string(kv)

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

【问题讨论】:

  • 欢迎来到 Stack Overflow!我编辑了您的问题,以便更容易找到代码格式。

标签: python kivy


【解决方案1】:

这是一个解决方案 :) 只需将定义颜色的属性添加到标签(在 kv 中)。然后在color-方法中相应地设置这个属性。

import kivy
kivy.require('1.8.0')

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



kv = """
RootWidget:
    orientation: 'vertical'

    TextInput:
        id: my_id
        text: 'text'
        on_text: root.color(self.text)

    Label:
        id: my_Label
        col: (1., 1., 0.)
        text: ' '
        canvas.before:
            Color:
                rgb: self.col
            Rectangle:
                size: self.size
                pos: self.pos
"""

class RootWidget(BoxLayout):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def color(self, inputtext):
        if len(inputtext)%3 == 0:
            col = (1,0,0)
        elif len(inputtext)%3 == 1:
            col = (0,1,0)
        else:
            col = (0,0,1)
        self.ids.my_Label.col = col

class TestApp(App):
    def build(self):
        return Builder.load_string(kv)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2015-04-18
    • 1970-01-01
    • 2012-10-21
    相关资源
    最近更新 更多