import tkinter as tk import tkinter.font as tkfont BG_COLOR = "#111018" FG_COLOR = "#E0E0E0" ACCENT_ORANGE = "#FF7518" class DynamicImgButton(tk.Button): """Ein Bild-Button, dessen Hintergrundgrafik automatisch mit der Textlänge mitwächst.""" def __init__(self, parent, text, img, img_active, command, min_px_width=None): self._assets = getattr(parent.winfo_toplevel(), "assets", None) self._font = tkfont.Font(family="Helvetica", size=11, weight="bold") self._min_px_width = min_px_width self._is_hovered = False # Erkennen, ob es der orange Hauptbutton (Höhe 50) oder der lila Auswahlbutton (Höhe 35) ist if self._assets and img == self._assets.btn_orange: self._style = "orange" self._height = 50 self._default_min = 200 else: self._style = "purple" self._height = 35 self._default_min = 150 self._img_norm, self._img_act = self._get_scaled_images(text) super().__init__( parent, text=text, image=self._img_norm, compound="center", command=command, bg=BG_COLOR, fg="white", font=self._font, bd=0, highlightthickness=0, activebackground=BG_COLOR, activeforeground="white", cursor="hand2" ) self.bind("", self._on_enter) self.bind("", self._on_leave) def _get_scaled_images(self, text_str): text_px = self._font.measure(str(text_str)) + 36 # 18px Polsterung links & rechts base_min = self._min_px_width if self._min_px_width else self._default_min target_w = max(base_min, text_px) if self._assets and hasattr(self._assets, "get_btn_pair"): return self._assets.get_btn_pair(self._style, target_w, self._height) return None, None def _on_enter(self, event=None): self._is_hovered = True if self["state"] != "disabled" and self._img_act: super().config(image=self._img_act) def _on_leave(self, event=None): self._is_hovered = False if self["state"] != "disabled" and self._img_norm: super().config(image=self._img_norm) def config(self, **kwargs): if "text" in kwargs: self._img_norm, self._img_act = self._get_scaled_images(kwargs["text"]) kwargs["image"] = self._img_act if (self._is_hovered and self._img_act) else self._img_norm super().config(**kwargs) configure = config def create_img_button(parent, text, img, img_active, command, width=None, min_px_width=None): return DynamicImgButton(parent, text, img, img_active, command, min_px_width=min_px_width)