Asynchronous operations
Learning how to perform actions which do not block the main thread
import threading
from gi.repository import Gtk, GdkPixbuf
from .services.wallpaper_service import WallPaperService
from .services.unsplash_service import UnSplashService
@Gtk.Template(resource_path='/com/yourusername/splash/window.ui')
class SplashWindow(Gtk.ApplicationWindow):
__gtype_name__ = 'SplashWindow'
wallpaper_container: Gtk.Image = Gtk.Template.Child()
shuffle_button: Gtk.Button = Gtk.Template.Child()
loading_spinner: Gtk.Spinner = Gtk.Template.Child()
unsplash_service: UnSplashService = UnSplashService()
wallpaper_service: WallPaperService = WallPaperService()
def shuffle_image(self):
self.loading_spinner.start()
random_wallpaper_url: str = self.unsplash_service.get_random_photo_url()
self.wallpaper_service.set_wallpaper_from_url(random_wallpaper_url)
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
self.wallpaper_service.splash_wallpaper_file_path,
width=1280,
height=720,
preserve_aspect_ratio=True,
)
self.wallpaper_container.set_from_pixbuf(pixbuf)
self.loading_spinner.stop()
def async_shuffle_image(self):
thread = threading.Thread(target=self.shuffle_image, daemon=True)
thread.start()
def shuffle_button_on_clicked(self, button: Gtk.Button):
self.async_shuffle_image()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.async_shuffle_image()
self.shuffle_button.connect("clicked", self.shuffle_button_on_clicked)

Last updated