0

我开始学习Kivy。下面的代码生成一个 10x10 的按钮网格:

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


class MyApp(App):
    def build(self):
        layout = GridLayout(cols=10)
        for i in range (1, 101):
            layout.add_widget(Button(text=str(i)))
        return layout

MyApp().run()

在此处输入图像描述

我想知道如何让每个按钮每秒打开和关闭,即按钮 1 打开 0.5 秒并关闭 0.5 秒,然后按钮 2 执行相同操作,并重复直到按钮 100?

4

1 回答 1

1

您可以使用kivy.clock来安排事件:

from functools import partial
from kivy.clock import Clock
from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button


class MyApp(App):
    def build(self):
        self.butts = []
        self.count = 0
        layout = GridLayout(cols=10)
        for i in range (1, 101):
            butt = Button(text=str(i))
            self.butts.append(butt)
            layout.add_widget(butt)

        # schedule call to self.flash every second
        Clock.schedule_interval(self.flash, 1.0)
        return layout

    def flash(self, dt):
        butt = self.butts[self.count]
        butt.state = 'down'

        # schedule call to set the button back to 'normal' in half a second
        Clock.schedule_once(partial(self.setNormal, butt), 0.5)
        self.count += 1
        if self.count == len(self.butts):
            # end the interval scheduling
            return False
        else:
            return True

    def setNormal(self, butt, dt):
        butt.state = 'normal'


MyApp().run()
于 2018-12-09T23:18:46.557 回答