代码之家  ›  专栏  ›  技术社区  ›  Jakub Bláha

Kivy中的更新窗口

  •  1
  • Jakub Bláha  · 技术社区  · 6 年前

    我想知道是否有可能 使现代化 基维的一扇窗户。

    我为什么需要这样做:

    我想制作一个调整窗口大小的动画。

    for i in range(100, 400):
        Window.size = (300, i)
        sleep(.01)
    

    现在它只需休眠3秒钟,然后调整大小。

    类似于Tkinter中的操作方式:

    我和特金特一起工作有一段时间了。在Tkinter中,可以这样做:

    w = tk.Tk()
    w.update()
    

    Kivy会怎么做?

    我们将非常感谢您的帮助!

    1 回复  |  直到 6 年前
        1
  •  2
  •   eyllanesc Yonghwan Shin    6 年前

    在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()