yahtzee-py/views/widgets.py

82 lines
3.3 KiB
Python
Raw Normal View History

2026-11-02 18:32:36 +00:00
import tkinter as tk
from PIL import Image, ImageTk
BG_COLOR = "#111018"
FG_COLOR = "#E0E0E0"
ACCENT_ORANGE = "#FF7518"
class ResizingBG(tk.Canvas):
"""Ein Canvas, das ein PIL-Bild automatisch an seine eigene Größe anpasst (Strecken)."""
def __init__(self, master, raw_image, **kwargs):
super().__init__(master, highlightthickness=0, bd=0, **kwargs)
self.raw_image = raw_image
self.bg_img = None
self.bind("<Configure>", self.on_resize)
def on_resize(self, event):
if self.raw_image and event.width > 10 and event.height > 10:
resized = self.raw_image.resize((event.width, event.height), Image.Resampling.LANCZOS)
self.bg_img = ImageTk.PhotoImage(resized)
self.delete("all")
self.create_image(0, 0, image=self.bg_img, anchor="nw")
class ImageDie(tk.Label):
"""Ein Würfel-Widget, das seine Größe dynamisch anpassen kann."""
def __init__(self, master, assets, command=None, **kwargs):
super().__init__(master, bg=BG_COLOR, bd=0, highlightthickness=0, cursor="hand2", **kwargs)
self.assets = assets
self.value = 1
self.held = False
self.command = command
self.current_size = 70
self.image_ref = None
self.bind("<Button-1>", lambda e: self.on_click())
self.update_image()
def on_click(self):
if self.command:
self.command()
def toggle_hold(self):
self.held = not self.held
self.config(bg="#8B0000" if self.held else BG_COLOR)
def set_value(self, val):
self.value = val
self.update_image()
def update_image(self):
if self.assets and self.value in self.assets.raw_dice and self.assets.raw_dice[self.value]:
raw = self.assets.raw_dice[self.value]
img = ImageTk.PhotoImage(raw.resize((self.current_size, self.current_size), Image.Resampling.LANCZOS))
self.image_ref = img
self.config(image=self.image_ref, text="")
else:
self.config(text=f"[{self.value}]", font=("Helvetica", 24), fg="white")
def show_anim_frame(self, frame_idx):
if self.assets and self.assets.raw_anim:
idx = frame_idx % len(self.assets.raw_anim)
raw = self.assets.raw_anim[idx]
img = ImageTk.PhotoImage(raw.resize((self.current_size, self.current_size), Image.Resampling.LANCZOS))
self.image_ref = img
self.config(image=self.image_ref)
def resize_die(self, new_size):
self.current_size = new_size
self.update_image()
def create_img_button(parent, text, img, img_active, command, width=None):
"""Erzeugt einen rahmenlosen Button mit optionalem Hover-Bild."""
btn = tk.Button(
parent, text=text, image=img, compound="center", command=command,
bg=BG_COLOR, fg="white", font=("Helvetica", 11, "bold"),
bd=0, highlightthickness=0, activebackground=BG_COLOR, activeforeground="white"
)
if not img and width:
btn.config(width=width, bg="#333", bd=1)
if img and img_active:
btn.bind("<Enter>", lambda e, b=btn: b.config(image=img_active) if b['state'] != 'disabled' else None)
btn.bind("<Leave>", lambda e, b=btn: b.config(image=img) if b['state'] != 'disabled' else None)
return btn