【问题标题】:Update window in KivyKivy 中的更新窗口
【发布时间】:2018-05-06 15:52:06
【问题描述】:

我想知道是否可以在 Kivy 中更新一个窗口。

为什么我需要这样做:

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

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

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

类似于在 Tkinter 中的操作方式:

我已经与 Tkinter 合作了一段时间。在 Tkinter 中会这样做:

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

Kivy 会如何做到这一点?

任何帮助将不胜感激!

【问题讨论】:

    标签: python window kivy


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-10
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多