我开始学习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 ?
答案 0 :(得分: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()