【问题标题】:Kivy - How to set duration for a piece of code?Kivy - 如何设置一段代码的持续时间?
【发布时间】:2018-09-22 15:29:18
【问题描述】:

我有:

Button:
    text: "SEQUENCE 2"
    size_hint: None, .16
    width: 225
    on_press:
        self.background_color = (1.7, 0, 1.7, 1)

我希望“self.background_color”在“on_press”之后的几秒钟后切换回正常(按下前的状态)。

我该怎么做呢?

编辑(在 .kv StackLayout 中是所需的位置。)

<ContScreen>:
    StackLayout
        orientation: "tb-rl"
        spacing: 15

        Button:
            text: "SEQUENCE 1"
            size_hint: None, .16
            width: 225

        Button:
            text: "SEQUENCE 2"
            size_hint: None, .16
            width: 225

如果无法集成到 .kv StackLayout 中,我该如何重新格式化它以基于 '' 方法工作。

【问题讨论】:

标签: python button kivy duration kivy-language


【解决方案1】:
  1. 使用Clock.create_trigger() 创建触发事件。
  2. 当持续时间到期或达到时,将按钮的 background_color 重置为默认颜色 [1, 1, 1, 1]

示例

main.py

​​>
from kivy.app import App
from kivy.uix.button import Button
from kivy.clock import Clock


class ButtonBackgroundColourDemo(Button):

    def on_press(self):
        print("\non_press")
        self.duration = 5
        self.background_color_event = Clock.create_trigger(self.set_background_colour, 1)
        self.background_color = (1.7, 0, 1.7, 1)
        self.background_color_event()

    def set_background_colour(self, dt):
        print("\tdt=", dt)
        self.duration -= 1
        if self.duration <= 0:
            self.background_color = [1, 1, 1, 1]    # reset to default colour
        else:
            self.background_color_event()


class Test(App):

    def build(self):
        return ButtonBackgroundColourDemo()


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

test.kv

#:kivy 1.11.0

<ButtonBackgroundColourDemo>:
    text: "SEQUENCE 2"
    size_hint: None, .16
    width: 225

输出

【讨论】:

    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多