Search code examples
pythonkivywindow

How to run a function when the Kivy window is un-minimised


I have an app that has a see through window- enter image description here

and when it un-minimised, I would like to take a screenshot to update the image but I don't know how to run a function when the window un-minimises.

I have tried

from io import BytesIO

from PIL import ImageGrab
from kivy.lang.builder import Builder
from kivy.clock import Clock
from kivy.core.image import Image as CoreImage
from kivy.core.window import Window as CoreWindow
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App


class Widget(FloatLayout):
    def __init__(self, *args, **kwargs):
        super(Widget, self).__init__(*args, **kwargs)

        CoreWindow.bind(left=self.on_pos, top=self.on_pos)

        Clock.schedule_once(self.take_screenshot, 0)

    def on_pos(self, _, pos):
        self.ids["parentScreenImage"].pos = 0 - CoreWindow.left, \
                                            (CoreWindow.top + CoreWindow.height) - self.ids["parentScreenImage"].size[1]

    def take_screenshot(self, _=None):
        img = ImageGrab.grab()
        data = BytesIO()
        img.save(data, format='png')
        data.seek(0)
        img = CoreImage(BytesIO(data.read()), ext='png')

        self.ids["parentScreenImage"].texture = img.texture
        self.ids["parentScreenImage"].size = img.size
        self.ids["parentScreenImage"].pos = 0 - CoreWindow.left, 0 - CoreWindow.top


class app(App):
    def on_unminimise(self):
        print("worked with on_unminimise")

    def on_un_minimise(self):
        print("worked with on_un_minimise")

    def on_resume(self):  # I think this only works on a phone
        print("worked with on_resume")

    def build(self):
        return Widget()


Builder.load_string("""
<Widget>:
    Image:
        id: parentScreenImage

        size_hint: None, None
""")
app().run()

but nothing gets printed. There also seems to be nothing on google either. Please help.

P.S. Out of interest, how would you run it when the window minimises


Solution

  • I think you can bind to the on_show event:

    class app(App):
        def on_show(self, window):
            print('show', window)
    
        def build(self):
            CoreWindow.bind(on_show=self.on_show)
            return Widget()