# -*- coding: utf-8 -*- # view/widgets/resizing_bg.py from __future__ import annotations import tkinter as tk from PIL import Image, ImageTk from resources.code_res.game_constants import BG_COLOR from view.layout_mode import LayoutMode class ResizingBG(tk.Canvas): def __init__(self, parent, assets): super().__init__(parent, bg=BG_COLOR, bd=0, highlightthickness=0) self.assets = assets self._bg_photo: ImageTk.PhotoImage | None = None self._last_size: tuple[bool, int, int] = (False, 0, 0) self._resize_job: str | None = None self.bind("", self._on_configure) self.bind("", self._on_destroy) try: pw, ph = parent.winfo_width(), parent.winfo_height() if pw >= 200 and ph >= 200: self._apply_bg(pw, ph) except Exception: pass def _on_destroy(self, event=None): if event is not None and event.widget is not self: return if self._resize_job is not None: try: self.after_cancel(self._resize_job) except Exception: pass self._resize_job = None def _on_configure(self, event): if event.widget is not self: return w, h = max(1, event.width), max(1, event.height) compact = LayoutMode.is_compact(w, h) if w < 100 or h < 100 or (compact, w, h) == self._last_size: return if self._resize_job is not None: try: self.after_cancel(self._resize_job) except Exception: pass self._resize_job = None if self._last_size[1] == 0: self._apply_bg(w, h) else: self._resize_job = self.after(35, self._apply_bg, w, h) def _apply_bg(self, w: int, h: int): self._resize_job = None if not self.winfo_exists(): return compact = LayoutMode.is_compact(w, h) if (compact, w, h) == self._last_size: return self._last_size = (compact, w, h) photo = self.assets.get_bg_patch_photo(w, h, 0, 0, w, h) if photo is None: return self._bg_photo = photo existing = self.find_withtag("root_bg_img") if existing: self.itemconfigure(existing[0], image=self._bg_photo) else: self.create_image(0, 0, image=self._bg_photo, anchor="nw", tags=("root_bg_img",)) self.tag_lower("root_bg_img") def clear_foreground(self): self.unbind("") self.bind("", self._on_configure) for sub in list(self.winfo_children()): try: sub.destroy() except Exception: pass keep_ids = set(self.find_withtag("root_bg_img")) for item_id in self.find_all(): if item_id not in keep_ids: self.delete(item_id)