在 GUI 中你不应该使用 sleep(),它是一个阻塞事件循环的任务,每个 GUI 都提供工具以友好的方式生成相同的效果,在 tkinter after() 的情况下(所以避免将sleep() 与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()