Jakub Bláha
Jakub Bláha

Reputation: 1609

Update window in Kivy

I want to know if it's possible to update a window in Kivy.

Why I need to do it:

I want to make an animation of window resizing.

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

Right now it just sleeps for 3 seconds and then it resizes.

Something similar to the way how to do it in Tkinter:

I have been working with Tkinter for a while. In Tkinter it would be done this way:

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

How would this be done with Kivy?

Any help will be highly appreciated!

Upvotes: 1

Views: 1449

Answers (1)

eyllanesc
eyllanesc

Reputation: 243897

In a GUI you should not use sleep(), it is a task that blocks the event loop, each GUI offers tools to generate the same effect in a way that is friendly, in the case of tkinter after() (so avoid using sleep() with update(), is a bad practice), in the case of kivy you can use 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()

or better, using Animation, the advantage of this implementation aside from having a more readable code, is that kivy handles when it must be updated in a way that does not consume resources unnecessarily:

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

Upvotes: 2

Related Questions