# -*- coding: utf-8 -*- # view/widgets/image_button.py import tkinter as tk from PIL import Image, ImageEnhance, ImageTk from resources.code_res.game_constants import BG_COLOR, FG_COLOR class ImageButton(tk.Label): """Rahmenloser Alpha-PNG-Button mit echtem Graufilter für inaktive Zustände (enabled=False).""" def __init__( self, parent, text: str, pil_normal, pil_hover, command, sound_mgr=None, width: int = 180, height: int = 42, font=("Helvetica", 11, "bold"), enabled: bool = True, ): try: parent_bg = parent.cget("bg") except Exception: parent_bg = BG_COLOR self._normal_photo = None self._hover_photo = None self._disabled_photo = None if pil_normal: resized_norm = pil_normal.resize((width, height), Image.Resampling.LANCZOS) self._normal_photo = ImageTk.PhotoImage(resized_norm) # Automatischer Grau- & Abdunklungsfilter für nicht klickbare Buttons gray_base = ImageEnhance.Color(resized_norm).enhance(0.0) dimmed = ImageEnhance.Brightness(gray_base).enhance(0.55) self._disabled_photo = ImageTk.PhotoImage(dimmed) if pil_hover: resized_hov = pil_hover.resize((width, height), Image.Resampling.LANCZOS) self._hover_photo = ImageTk.PhotoImage(resized_hov) self._sound_mgr = sound_mgr self._user_cmd = command self._enabled = bool(enabled) init_img = self._normal_photo if self._enabled else self._disabled_photo init_fg = FG_COLOR if self._enabled else "#777282" super().__init__( parent, text=text, image=init_img if init_img else "", compound="center", font=font, fg=init_fg, bg=parent_bg, bd=0, padx=0, pady=0, highlightthickness=0, cursor="hand2" if self._enabled else "arrow", ) self.bind("", self._on_enter) self.bind("", self._on_leave) self.bind("", self._on_click) def set_enabled(self, enabled: bool): self._enabled = bool(enabled) if self._enabled: self.configure( image=self._normal_photo if self._normal_photo else "", fg=FG_COLOR, cursor="hand2", ) else: self.configure( image=self._disabled_photo if self._disabled_photo else "", fg="#777282", cursor="arrow", ) def _on_enter(self, _event): if not self._enabled: return if self._hover_photo: self.configure(image=self._hover_photo, fg="#ffffff") else: self.configure(fg="#ffffff") def _on_leave(self, _event): if not self._enabled: return if self._normal_photo: self.configure(image=self._normal_photo, fg=FG_COLOR) else: self.configure(fg=FG_COLOR) def _on_click(self, _event): if not self._enabled: return if self._sound_mgr: self._sound_mgr.play("click") if self._user_cmd: self._user_cmd()