在GUI中,不应使用
sleep()
,这是一项阻止事件循环的任务,在tkinter的情况下,每个GUI都提供了以友好的方式生成相同效果的工具
after()
(因此避免使用
睡眠()
具有
update()
,是一种不好的做法),对于kivy,您可以使用
Clock
:
import kivy
from kivy.app import App
from kivy.clock import Clock
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.config import Config
Config.set('graphics', 'width', '300')
Config.set('graphics', 'height', '100')
Config.write()
Window.size = (300, 100)
class ButtonAnimation(Button):
def __init__(self, **kwargs):
Button.__init__(self, **kwargs)
self.bind(on_press=self.start_animation)
def start_animation(self, *args):
self.counter = 100
self.clock = Clock.schedule_interval(self.animation, 0.01)
def animation(self, *args):
Window.size = (300, self.counter)
self.counter += 1
if self.counter > 400:
self.clock.cancel()
class MyApp(App):
def build(self):
root = ButtonAnimation(text='Press me')
return root
if __name__ == '__main__':
MyApp().run()
或者更好,使用
Animation
,除了具有更可读的代码外,此实现的优点是kivy可以处理必须以不必要消耗资源的方式进行更新的情况:
import kivy
from kivy.app import App
from kivy.core.window import Window
from kivy.animation import Animation
from kivy.uix.button import Button
from kivy.config import Config
Config.set('graphics', 'width', '300')
Config.set('graphics', 'height', '100')
Config.write()
Window.size = (300, 100)
class ButtonAnimation(Button):
def __init__(self, **kwargs):
Button.__init__(self, **kwargs)
self.bind(on_press=self.start_animation)
def start_animation(self, *args):
anim = Animation(size=(300, 400), step=0.01)
anim.start(Window)
class MyApp(App):
def build(self):
root = ButtonAnimation(text='Press me')
return root
if __name__ == '__main__':
MyApp().run()