the_goth_cardgame_collection/view/widgets/resizing_bg.py

92 lines
2.9 KiB
Python
Raw Normal View History

2026-11-14 04:25:51 +00:00
# -*- coding: utf-8 -*-
# view/widgets/resizing_bg.py
from __future__ import annotations
2026-11-14 04:25:51 +00:00
import tkinter as tk
from PIL import Image, ImageTk
from resources.code_res.game_constants import BG_COLOR
from view.layout_mode import LayoutMode
2026-11-14 04:25:51 +00:00
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
2026-11-14 04:25:51 +00:00
self.bind("<Configure>", self._on_configure)
self.bind("<Destroy>", 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
2026-11-14 04:25:51 +00:00
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("<Configure>")
self.bind("<Configure>", 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)